<!DOCTYPE html>
<html class="writer-html5" lang="en" data-content_root="../../">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>pyokx.rest_handling &mdash; AntBot 0.0.1 documentation</title>
      <link rel="stylesheet" type="text/css" href="../../_static/pygments.css?v=80d5e7a1" />
      <link rel="stylesheet" type="text/css" href="../../_static/css/theme.css?v=19f00094" />
      <link rel="stylesheet" type="text/css" href="../../_static/graphviz.css?v=eafc0fe6" />

  
  <!--[if lt IE 9]>
    <script src="../../_static/js/html5shiv.min.js"></script>
  <![endif]-->
  
        <script src="../../_static/jquery.js?v=5d32c60e"></script>
        <script src="../../_static/_sphinx_javascript_frameworks_compat.js?v=2cd50e6c"></script>
        <script src="../../_static/documentation_options.js?v=d45e8c67"></script>
        <script src="../../_static/doctools.js?v=888ff710"></script>
        <script src="../../_static/sphinx_highlight.js?v=dc90522c"></script>
    <script src="../../_static/js/theme.js"></script>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" /> 
</head>

<body class="wy-body-for-nav"> 
  <div class="wy-grid-for-nav">
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >

          
          
          <a href="../../index.html" class="icon icon-home">
            AntBot
          </a>
              <div class="version">
                0.0.1
              </div>
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" aria-label="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>
        </div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
              <p class="caption" role="heading"><span class="caption-text">Contents:</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../autodocumentation_python.html">autodocumentation_python</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../firebase_tools.BaseClasses.html">firebase_tools.BaseClasses</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../firebase_tools.FirestoreClient.html">firebase_tools.FirestoreClient</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../firebase_tools.authenticate.html">firebase_tools.authenticate</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../h2o_dashboard.dashboard.html">h2o_dashboard.dashboard</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../h2o_dashboard.pages.documentation_page.html">h2o_dashboard.pages.documentation_page</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../h2o_dashboard.pages.okx_dashbaord_page.okx_antbot_okx_premium_indicator_handler.html">h2o_dashboard.pages.okx_dashbaord_page.okx_antbot_okx_premium_indicator_handler</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../h2o_dashboard.pages.okx_dashbaord_page.okx_dashboard_page.html">h2o_dashboard.pages.okx_dashbaord_page.okx_dashboard_page</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../h2o_dashboard.pages.okx_streams.html">h2o_dashboard.pages.okx_streams</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../h2o_dashboard.pages.overview_page.html">h2o_dashboard.pages.overview_page</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../h2o_dashboard.util.html">h2o_dashboard.util</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../h2o_dashboard.wave_auth.html">h2o_dashboard.wave_auth</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.Futures_Exchange_Client.html">pyokx.Futures_Exchange_Client</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.InstrumentSearcher.html">pyokx.InstrumentSearcher</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.data_structures.html">pyokx.data_structures</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.Account.html">pyokx.low_rest_api.Account</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.BlockTrading.html">pyokx.low_rest_api.BlockTrading</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.Convert.html">pyokx.low_rest_api.Convert</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.CopyTrading.html">pyokx.low_rest_api.CopyTrading</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.Earning.html">pyokx.low_rest_api.Earning</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.FDBroker.html">pyokx.low_rest_api.FDBroker</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.Funding.html">pyokx.low_rest_api.Funding</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.Grid.html">pyokx.low_rest_api.Grid</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.MarketData.html">pyokx.low_rest_api.MarketData</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.NDBroker.html">pyokx.low_rest_api.NDBroker</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.PublicData.html">pyokx.low_rest_api.PublicData</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.SpreadTrading.html">pyokx.low_rest_api.SpreadTrading</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.Status.html">pyokx.low_rest_api.Status</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.SubAccount.html">pyokx.low_rest_api.SubAccount</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.Trade.html">pyokx.low_rest_api.Trade</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.TradingData.html">pyokx.low_rest_api.TradingData</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.client.html">pyokx.low_rest_api.client</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.consts.html">pyokx.low_rest_api.consts</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.exceptions.html">pyokx.low_rest_api.exceptions</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.low_rest_api.utils.html">pyokx.low_rest_api.utils</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.market_data_service.WssMarketDataService.html">pyokx.okx_market_maker.market_data_service.WssMarketDataService</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.market_data_service.model.Instrument.html">pyokx.okx_market_maker.market_data_service.model.Instrument</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.market_data_service.model.MarkPx.html">pyokx.okx_market_maker.market_data_service.model.MarkPx</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.market_data_service.model.OrderBook.html">pyokx.okx_market_maker.market_data_service.model.OrderBook</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.market_data_service.model.Tickers.html">pyokx.okx_market_maker.market_data_service.model.Tickers</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.order_management_service.WssOrderManagementService.html">pyokx.okx_market_maker.order_management_service.WssOrderManagementService</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.order_management_service.model.Order.html">pyokx.okx_market_maker.order_management_service.model.Order</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.order_management_service.model.OrderRequest.html">pyokx.okx_market_maker.order_management_service.model.OrderRequest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.position_management_service.WssPositionManagementService.html">pyokx.okx_market_maker.position_management_service.WssPositionManagementService</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.position_management_service.model.Account.html">pyokx.okx_market_maker.position_management_service.model.Account</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.position_management_service.model.BalanceAndPosition.html">pyokx.okx_market_maker.position_management_service.model.BalanceAndPosition</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.position_management_service.model.Positions.html">pyokx.okx_market_maker.position_management_service.model.Positions</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.run_sample_market_maker.html">pyokx.okx_market_maker.run_sample_market_maker</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.settings.html">pyokx.okx_market_maker.settings</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.strategy.BaseStrategy.html">pyokx.okx_market_maker.strategy.BaseStrategy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.strategy.SampleMM.html">pyokx.okx_market_maker.strategy.SampleMM</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.strategy.model.StrategyMeasurement.html">pyokx.okx_market_maker.strategy.model.StrategyMeasurement</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.strategy.model.StrategyOrder.html">pyokx.okx_market_maker.strategy.model.StrategyOrder</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.strategy.params.ParamsLoader.html">pyokx.okx_market_maker.strategy.params.ParamsLoader</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.strategy.risk.RiskCalculator.html">pyokx.okx_market_maker.strategy.risk.RiskCalculator</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.strategy.risk.RiskSnapshot.html">pyokx.okx_market_maker.strategy.risk.RiskSnapshot</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.tests.test_strategy.html">pyokx.okx_market_maker.tests.test_strategy</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.utils.InstrumentUtil.html">pyokx.okx_market_maker.utils.InstrumentUtil</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.utils.OkxEnum.html">pyokx.okx_market_maker.utils.OkxEnum</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.utils.TdModeUtil.html">pyokx.okx_market_maker.utils.TdModeUtil</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.okx_market_maker.utils.WsOrderUtil.html">pyokx.okx_market_maker.utils.WsOrderUtil</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.redis_structured_reports.html">pyokx.redis_structured_reports</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.redis_structured_streams.html">pyokx.redis_structured_streams</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.rest_handling.html">pyokx.rest_handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.rest_messages_service.html">pyokx.rest_messages_service</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.strategy_handling.html">pyokx.strategy_handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.AccountTest.html">pyokx.test.AccountTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.BlockTradingTest.html">pyokx.test.BlockTradingTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.BrokerTest.html">pyokx.test.BrokerTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.ConvertTest.html">pyokx.test.ConvertTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.CopyTradingTest.html">pyokx.test.CopyTradingTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.EarningTest.html">pyokx.test.EarningTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.FundingTest.html">pyokx.test.FundingTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.GridTest.html">pyokx.test.GridTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.MarketTest.html">pyokx.test.MarketTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.PublicDataTest.html">pyokx.test.PublicDataTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.SpreadTest.html">pyokx.test.SpreadTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.StackingTest.html">pyokx.test.StackingTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.SubAccountTest.html">pyokx.test.SubAccountTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.TradeTest.html">pyokx.test.TradeTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.TradingDataTest.html">pyokx.test.TradingDataTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.WsPrivateAsyncTest.html">pyokx.test.WsPrivateAsyncTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.test.WsPublicAsyncTest.html">pyokx.test.WsPublicAsyncTest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.websocket_handling.html">pyokx.websocket_handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.ws_clients.WebSocketFactory.html">pyokx.ws_clients.WebSocketFactory</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.ws_clients.WsPprivateAsync.html">pyokx.ws_clients.WsPprivateAsync</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.ws_clients.WsPublicAsync.html">pyokx.ws_clients.WsPublicAsync</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.ws_clients.WsUtils.html">pyokx.ws_clients.WsUtils</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../pyokx.ws_data_structures.html">pyokx.ws_data_structures</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../redis_tools.config.html">redis_tools.config</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../redis_tools.consumers.html">redis_tools.consumers</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../redis_tools.utils.html">redis_tools.utils</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../rest_app.html">rest_app</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../routers.api_keys.html">routers.api_keys</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../routers.login.html">routers.login</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../routers.okx.html">routers.okx</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../routers.okx_authentication.html">routers.okx_authentication</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../routers.signup.html">routers.signup</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../shared.command_execution.html">shared.command_execution</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../shared.config.html">shared.config</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../shared.configuration_parser.html">shared.configuration_parser</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../shared.data_processing_utils.html">shared.data_processing_utils</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../shared.file_directory_ops.html">shared.file_directory_ops</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../shared.logging.html">shared.logging</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../shared.string_dict_utils.html">shared.string_dict_utils</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../shared.tmp_shared.html">shared.tmp_shared</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../tradingview_tools.tradingview_widgets.html">tradingview_tools.tradingview_widgets</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../websocket_app.html">websocket_app</a></li>
</ul>

        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" >
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../index.html">AntBot</a>
      </nav>

      <div class="wy-nav-content">
        <div class="rst-content">
          <div role="navigation" aria-label="Page navigation">
  <ul class="wy-breadcrumbs">
      <li><a href="../../index.html" class="icon icon-home" aria-label="Home"></a></li>
          <li class="breadcrumb-item"><a href="../index.html">Module code</a></li>
      <li class="breadcrumb-item active">pyokx.rest_handling</li>
      <li class="wy-breadcrumbs-aside">
      </li>
  </ul>
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
             
  <h1>Source code for pyokx.rest_handling</h1><div class="highlight"><pre>
<span></span>
<span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">json</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">random</span>
<span class="kn">import</span> <span class="nn">re</span>
<span class="kn">import</span> <span class="nn">string</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">from</span> <span class="nn">pprint</span> <span class="kn">import</span> <span class="n">pprint</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span><span class="p">,</span> <span class="n">Any</span><span class="p">,</span> <span class="n">Union</span>
<span class="kn">from</span> <span class="nn">urllib.error</span> <span class="kn">import</span> <span class="n">HTTPError</span>

<span class="kn">import</span> <span class="nn">requests</span>

<span class="kn">from</span> <span class="nn">pyokx.InstrumentSearcher</span> <span class="kn">import</span> <span class="n">InstrumentSearcher</span>
<span class="kn">from</span> <span class="nn">pyokx.data_structures</span> <span class="kn">import</span> <span class="p">(</span><span class="n">Order</span><span class="p">,</span> <span class="n">Cancelled_Order</span><span class="p">,</span> <span class="n">Order_Placement_Return</span><span class="p">,</span>
                                   <span class="n">Position</span><span class="p">,</span> <span class="n">Closed_Position</span><span class="p">,</span> <span class="n">Ticker</span><span class="p">,</span>
                                   <span class="n">Algo_Order</span><span class="p">,</span> <span class="n">Algo_Order_Placement_Return</span><span class="p">,</span>
                                   <span class="n">AccountBalanceDetails</span><span class="p">,</span> <span class="n">AccountBalanceData</span><span class="p">,</span>
                                   <span class="n">AccountConfigData</span><span class="p">,</span> <span class="n">MaxOrderSizeData</span><span class="p">,</span> <span class="n">MaxAvailSizeData</span><span class="p">,</span> <span class="n">Cancelled_Algo_Order</span><span class="p">,</span>
                                   <span class="n">Orderbook_Snapshot</span><span class="p">,</span> <span class="n">Bid</span><span class="p">,</span> <span class="n">Ask</span><span class="p">,</span>
                                   <span class="n">Simplified_Balance_Details</span><span class="p">,</span> <span class="n">InstrumentStatusReport</span><span class="p">,</span>
                                   <span class="n">OKXPremiumIndicatorSignalRequestForm</span><span class="p">,</span> <span class="n">FillEntry</span><span class="p">,</span> <span class="n">OKXSignalInput</span><span class="p">,</span> <span class="n">DCAInputParameters</span><span class="p">,</span>
                                   <span class="n">DCAOrderParameters</span><span class="p">)</span>
<span class="kn">from</span> <span class="nn">pyokx.okx_market_maker.utils.OkxEnum</span> <span class="kn">import</span> <span class="n">InstType</span>
<span class="kn">from</span> <span class="nn">pyokx.redis_structured_streams</span> <span class="kn">import</span> <span class="n">get_instruments_searcher_from_redis</span>
<span class="kn">from</span> <span class="nn">redis_tools.utils</span> <span class="kn">import</span> <span class="n">init_async_redis</span>
<span class="kn">from</span> <span class="nn">shared</span> <span class="kn">import</span> <span class="n">logging</span>
<span class="kn">from</span> <span class="nn">shared.tmp_shared</span> <span class="kn">import</span> <span class="n">calculate_tp_stop_prices_usd</span><span class="p">,</span> <span class="n">calculate_sl_stop_prices_usd</span><span class="p">,</span> <span class="n">ccy_usd_to_contracts</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">setup_logger</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>

<span class="kn">from</span> <span class="nn">pyokx</span> <span class="kn">import</span> <span class="n">okx_client</span><span class="p">,</span> <span class="n">tradeAPI</span><span class="p">,</span> <span class="n">marketAPI</span><span class="p">,</span> <span class="n">accountAPI</span><span class="p">,</span> <span class="n">publicAPI</span><span class="p">,</span> <span class="n">ENFORCED_INSTRUMENT_TYPE</span>  <span class="c1"># noqa</span>

<span class="n">REDIS_STREAM_MAX_LEN</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">getenv</span><span class="p">(</span><span class="s1">&#39;REDIS_STREAM_MAX_LEN&#39;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">))</span>

<span class="sd">&quot;&quot;&quot;NOTE: THE MODULE NEEDS TO BE UPDATED WITH ENUMS AND STRUCTURED DATA TYPES WHERE APPLICABLE&quot;&quot;&quot;</span>


<div class="viewcode-block" id="get_request_data">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_request_data">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_request_data</span><span class="p">(</span><span class="n">returned_data</span><span class="p">,</span> <span class="n">target_data_structure</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Processes the returned data from an API call, mapping it to the specified data structure.</span>

<span class="sd">    Args:</span>
<span class="sd">        returned_data (dict): The raw data returned from the API call.</span>
<span class="sd">        target_data_structure (class): The class to which the returned data items will be mapped.</span>

<span class="sd">    Returns:</span>
<span class="sd">        List[Any]: A list of instances of the target data structure class, populated with the returned data.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="c1"># print(f&#39;{returned_data = }&#39;)</span>
    <span class="k">if</span> <span class="n">returned_data</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="s2">&quot;0&quot;</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Unsuccessful </span><span class="si">{</span><span class="n">target_data_structure</span><span class="si">}</span><span class="s2"> request，</span><span class="se">\n</span><span class="s2">  error_code = &quot;</span><span class="p">,</span> <span class="n">returned_data</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">],</span>
              <span class="s2">&quot;, </span><span class="se">\n</span><span class="s2">  Error_message = &quot;</span><span class="p">,</span>
              <span class="n">returned_data</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">])</span>
        <span class="k">return</span> <span class="p">[]</span>

    <span class="n">structured_data</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">data</span> <span class="ow">in</span> <span class="n">returned_data</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">]:</span>
        <span class="n">structured_data</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">target_data_structure</span><span class="p">(</span><span class="o">**</span><span class="n">data</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">structured_data</span></div>



<div class="viewcode-block" id="get_ticker_with_higher_volume">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_ticker_with_higher_volume">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_ticker_with_higher_volume</span><span class="p">(</span><span class="n">seed_symbol_name</span><span class="p">,</span> <span class="n">instrument_type</span><span class="o">=</span><span class="s2">&quot;FUTURES&quot;</span><span class="p">,</span> <span class="n">top_n</span><span class="o">=</span><span class="mi">1</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Retrieves the ticker(s) with the highest trading volume for a given seed symbol and instrument type.</span>
<span class="sd">    Optionally, returns the top N tickers sorted by volume.</span>

<span class="sd">    Args:</span>
<span class="sd">        seed_symbol_name (str): The base symbol to search for.</span>
<span class="sd">        instrument_type (str, optional): The type of instrument (e.g., &quot;FUTURES&quot;). Defaults to &quot;FUTURES&quot;.</span>
<span class="sd">        top_n (int, optional): The number of top-volume tickers to return. Defaults to 1.</span>

<span class="sd">    Returns:</span>
<span class="sd">        List[Ticker]: A list of tickers, sorted by volume, up to the specified top_n number.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">seed_symbol_name</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>  <span class="c1"># tickers_data = okx_client.marketAPI.get_tickers(instType=instrument_type)</span>

    <span class="c1"># raise DeprecationWarning(&quot;This function is deprecated. Waiting to update to Structured Data Types.&quot;)</span>
    <span class="n">all_positions</span> <span class="o">=</span> <span class="n">okx_client</span><span class="o">.</span><span class="n">accountAPI</span><span class="o">.</span><span class="n">get_positions</span><span class="p">(</span><span class="n">instType</span><span class="o">=</span><span class="n">instrument_type</span><span class="p">)</span>
    <span class="n">all_position_symbols</span> <span class="o">=</span> <span class="p">[</span><span class="n">position</span><span class="p">[</span><span class="s1">&#39;instId&#39;</span><span class="p">]</span> <span class="k">for</span> <span class="n">position</span> <span class="ow">in</span> <span class="n">all_positions</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">]]</span>
    <span class="n">tickers_data</span> <span class="o">=</span> <span class="n">okx_client</span><span class="o">.</span><span class="n">marketAPI</span><span class="o">.</span><span class="n">get_tickers</span><span class="p">(</span><span class="n">instType</span><span class="o">=</span><span class="n">instrument_type</span><span class="p">)</span>

    <span class="c1"># If any tickers data are returned, find the ticker data for the symbol we are trading</span>
    <span class="c1"># fixme this is a hack since okx is returning multiple instId&#39;s</span>
    <span class="n">_highest_volume</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">_highest_volume_ticker</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="n">_ticker_data</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="n">_top_n_tickers_highest_day_volume</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="k">for</span> <span class="n">ticker_data</span> <span class="ow">in</span> <span class="n">tickers_data</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">]:</span>
        <span class="k">if</span> <span class="n">ticker_data</span><span class="p">[</span><span class="s1">&#39;instId&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="n">seed_symbol_name</span><span class="p">):</span>
            <span class="n">_ticker_data</span> <span class="o">=</span> <span class="n">ticker_data</span>
            <span class="n">_volume</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">ticker_data</span><span class="p">[</span><span class="s1">&#39;volCcy24h&#39;</span><span class="p">])</span>
            <span class="n">_top_n_tickers_highest_day_volume</span><span class="p">[</span><span class="n">_volume</span><span class="p">]</span> <span class="o">=</span> <span class="n">ticker_data</span>

    <span class="c1"># sort the volumes in descending order</span>
    <span class="n">_sorted_volumes</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">_top_n_tickers_highest_day_volume</span><span class="o">.</span><span class="n">keys</span><span class="p">(),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
    <span class="n">_top_n_tickers</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">_volume</span> <span class="ow">in</span> <span class="n">_sorted_volumes</span><span class="p">:</span>
        <span class="n">_top_n_tickers</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">_top_n_tickers_highest_day_volume</span><span class="p">[</span><span class="n">_volume</span><span class="p">])</span>

    <span class="n">tickers</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">_ticker_data</span> <span class="ow">in</span> <span class="n">_top_n_tickers</span><span class="p">[:</span><span class="n">top_n</span><span class="p">]:</span>
        <span class="n">tickers</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">Ticker</span><span class="p">(</span><span class="o">**</span><span class="n">_ticker_data</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">tickers</span></div>


    <span class="c1"># get the tickers for the top 5 volumes</span>


<div class="viewcode-block" id="assert_okx_account_level">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.assert_okx_account_level">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">assert_okx_account_level</span><span class="p">(</span><span class="n">account_level</span><span class="p">:</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">]):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Validates and sets the OKX account level, ensuring it is one of the acceptable levels.</span>

<span class="sd">    Args:</span>
<span class="sd">        account_level (list[int]): The account level to be validated and set. Acceptable levels are 1, 2, 3, and 4.</span>

<span class="sd">    Raises:</span>
<span class="sd">        AssertionError: If the account level is not one of the acceptable levels or if the account level could not be set.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">raise</span> <span class="ne">DeprecationWarning</span><span class="p">(</span><span class="s2">&quot;This function is deprecated. Waiting to update to Structured Data Types.&quot;</span><span class="p">)</span>
    <span class="n">ACCLV_MAPPING</span> <span class="o">=</span> <span class="p">{</span>
        <span class="mi">1</span><span class="p">:</span> <span class="s2">&quot;Simple mode&quot;</span><span class="p">,</span>
        <span class="mi">2</span><span class="p">:</span> <span class="s2">&quot;Single-currency margin mode&quot;</span><span class="p">,</span>
        <span class="mi">3</span><span class="p">:</span> <span class="s2">&quot;Multi-currency margin mode&quot;</span><span class="p">,</span>
        <span class="mi">4</span><span class="p">:</span> <span class="s2">&quot;Portfolio margin mode&quot;</span>
    <span class="p">}</span>

    <span class="k">assert</span> <span class="n">account_level</span> <span class="ow">in</span> <span class="n">ACCLV_MAPPING</span><span class="o">.</span><span class="n">keys</span><span class="p">(),</span> <span class="sa">f</span><span class="s2">&quot;Account level must be one of </span><span class="si">{</span><span class="n">ACCLV_MAPPING</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span><span class="si">}</span><span class="s2">&quot;</span>

    <span class="c1"># Set account level</span>
    <span class="n">result_set_account_level</span> <span class="o">=</span> <span class="n">accountAPI</span><span class="o">.</span><span class="n">set_account_level</span><span class="p">(</span><span class="n">acctLv</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">result_set_account_level</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">result_set_account_level</span><span class="p">[</span><span class="s1">&#39;code&#39;</span><span class="p">]</span> <span class="o">!=</span> <span class="s2">&quot;0&quot;</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Unsuccessful request，</span><span class="se">\n</span><span class="s2">  error_code = &quot;</span><span class="p">,</span> <span class="n">result_set_account_level</span><span class="p">[</span><span class="s1">&#39;code&#39;</span><span class="p">],</span> <span class="s2">&quot;, </span><span class="se">\n</span><span class="s2">  Error_message = &quot;</span><span class="p">,</span>
              <span class="n">result_set_account_level</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">])</span>

    <span class="c1"># Get account configuration</span>
    <span class="n">result_get_account_config</span> <span class="o">=</span> <span class="n">accountAPI</span><span class="o">.</span><span class="n">get_account_config</span><span class="p">()</span>

    <span class="k">if</span> <span class="n">result_get_account_config</span><span class="p">[</span><span class="s1">&#39;code&#39;</span><span class="p">]</span> <span class="o">==</span> <span class="s2">&quot;0&quot;</span><span class="p">:</span>
        <span class="n">acctLv</span> <span class="o">=</span> <span class="n">result_get_account_config</span><span class="p">[</span><span class="s2">&quot;data&quot;</span><span class="p">][</span><span class="mi">0</span><span class="p">][</span><span class="s2">&quot;acctLv&quot;</span><span class="p">]</span>
        <span class="k">assert</span> <span class="n">acctLv</span> <span class="o">==</span> <span class="n">account_level</span><span class="p">,</span> <span class="sa">f</span><span class="s2">&quot;Account level was not set to </span><span class="si">{</span><span class="n">ACCLV_MAPPING</span><span class="p">[</span><span class="n">account_level</span><span class="p">]</span><span class="si">}</span><span class="s2">&quot;</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Unsuccessful `assert_okx_account_level` request，</span><span class="se">\n</span><span class="s2">  error_code = &quot;</span><span class="p">,</span> <span class="n">result_get_account_config</span><span class="p">[</span><span class="s1">&#39;code&#39;</span><span class="p">],</span>
              <span class="s2">&quot;, </span><span class="se">\n</span><span class="s2">  Error_message = &quot;</span><span class="p">,</span>
              <span class="n">result_get_account_config</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">])</span></div>



<div class="viewcode-block" id="is_valid_alphanumeric">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.is_valid_alphanumeric">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">is_valid_alphanumeric</span><span class="p">(</span><span class="n">string</span><span class="p">,</span> <span class="n">max_length</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Validates if the input string is alphanumeric and conforms to the specified maximum length.</span>

<span class="sd">    Args:</span>
<span class="sd">        string (str): The string to validate.</span>
<span class="sd">        max_length (int): The maximum allowable length for the string.</span>

<span class="sd">    Returns:</span>
<span class="sd">        bool: True if the string is alphanumeric and does not exceed the max_length, False otherwise.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">return</span> <span class="nb">bool</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;^[a-zA-Z0-9]{1,&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">max_length</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;}$&#39;</span><span class="p">,</span> <span class="n">string</span><span class="p">))</span></div>



<div class="viewcode-block" id="get_all_orders">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_all_orders">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_all_orders</span><span class="p">(</span><span class="n">instType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">instId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Fetches all orders matching the given criteria from the trading API.</span>

<span class="sd">    Args:</span>
<span class="sd">        instType (str, optional): The type of instrument to fetch orders for (e.g., &quot;FUTURES&quot;).</span>
<span class="sd">        instId (str, optional): The specific instrument ID to fetch orders for.</span>

<span class="sd">    Returns:</span>
<span class="sd">        List[Order]: A list of orders that match the given criteria.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">params</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="k">if</span> <span class="n">instType</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instType&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instType</span>
    <span class="k">if</span> <span class="n">instId</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instId&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instId</span>
    <span class="k">return</span> <span class="k">await</span> <span class="n">get_request_data</span><span class="p">(</span><span class="n">tradeAPI</span><span class="o">.</span><span class="n">get_order_list</span><span class="p">(</span><span class="o">**</span><span class="n">params</span><span class="p">),</span> <span class="n">Order</span><span class="p">)</span></div>



<div class="viewcode-block" id="cancel_all_orders">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.cancel_all_orders">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">cancel_all_orders</span><span class="p">(</span><span class="n">orders_list</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">Order</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">instType</span><span class="p">:</span> <span class="n">InstType</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">instId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Cancels all or specific orders based on the provided parameters.</span>

<span class="sd">    Args:</span>
<span class="sd">        orders_list (List[Order], optional): A list of specific orders to cancel. If not provided, all orders are cancelled.</span>
<span class="sd">        instType (InstType, optional): The type of instrument to cancel orders for.</span>
<span class="sd">        instId (str, optional): The specific instrument ID to cancel orders for.</span>

<span class="sd">    Returns:</span>
<span class="sd">        List[Cancelled_Order]: A list of the orders that were successfully cancelled.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">orders_list</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">params</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">if</span> <span class="n">instType</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instType&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instType</span>
        <span class="k">if</span> <span class="n">instId</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instId&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instId</span>
        <span class="n">orders_list</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_all_orders</span><span class="p">(</span><span class="o">**</span><span class="n">params</span><span class="p">)</span>
    <span class="c1"># cancelled_orders = []</span>
    <span class="n">orders_to_cancel</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">order</span> <span class="ow">in</span> <span class="n">orders_list</span><span class="p">:</span>
        <span class="n">orders_to_cancel</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">order</span><span class="p">)</span>

    <span class="c1"># Batch Cancel Orders</span>
    <span class="n">cancelled_orders</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_request_data</span><span class="p">(</span><span class="n">tradeAPI</span><span class="o">.</span><span class="n">cancel_multiple_orders</span><span class="p">(</span>
        <span class="n">orders_data</span><span class="o">=</span><span class="p">[</span>
            <span class="p">{</span><span class="s1">&#39;instId&#39;</span><span class="p">:</span> <span class="n">order</span><span class="o">.</span><span class="n">instId</span><span class="p">,</span>
             <span class="s1">&#39;ordId&#39;</span><span class="p">:</span> <span class="n">order</span><span class="o">.</span><span class="n">ordId</span><span class="p">,</span>
             <span class="p">}</span> <span class="k">for</span> <span class="n">order</span> <span class="ow">in</span> <span class="n">orders_to_cancel</span>
        <span class="p">]</span>
    <span class="p">),</span> <span class="n">Cancelled_Order</span><span class="p">)</span>

    <span class="c1">#</span>
    <span class="k">return</span> <span class="n">cancelled_orders</span></div>



<div class="viewcode-block" id="close_position">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.close_position">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">close_position</span><span class="p">(</span><span class="n">instId</span><span class="p">,</span> <span class="n">mgnMode</span><span class="p">,</span> <span class="n">posSide</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">ccy</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">autoCxl</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">clOrdId</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">tag</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Closes a position based on the given parameters.</span>

<span class="sd">    :param instId: The instrument ID for the position to be closed.</span>
<span class="sd">    :type instId: str</span>
<span class="sd">    :param mgnMode: The margin mode for the position (e.g., &#39;isolated&#39;, &#39;cross&#39;).</span>
<span class="sd">    :type mgnMode: str</span>
<span class="sd">    :param posSide: The position side (e.g., &#39;long&#39;, &#39;short&#39;). Defaults to an empty string.</span>
<span class="sd">    :type posSide: str, optional</span>
<span class="sd">    :param ccy: The currency used for the position. Defaults to an empty string.</span>
<span class="sd">    :type ccy: str, optional</span>
<span class="sd">    :param autoCxl: Automatically cancel the position. Defaults to an empty string.</span>
<span class="sd">    :type autoCxl: str, optional</span>
<span class="sd">    :param clOrdId: The client order ID. Defaults to an empty string.</span>
<span class="sd">    :type clOrdId: str, optional</span>
<span class="sd">    :param tag: A tag for the position. Defaults to an empty string.</span>
<span class="sd">    :type tag: str, optional</span>
<span class="sd">    :returns: The response from the position close request.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">params</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;instId&#39;</span><span class="p">:</span> <span class="n">instId</span><span class="p">,</span> <span class="s1">&#39;mgnMode&#39;</span><span class="p">:</span> <span class="n">mgnMode</span><span class="p">,</span> <span class="s1">&#39;posSide&#39;</span><span class="p">:</span> <span class="n">posSide</span><span class="p">,</span> <span class="s1">&#39;ccy&#39;</span><span class="p">:</span> <span class="n">ccy</span><span class="p">,</span> <span class="s1">&#39;autoCxl&#39;</span><span class="p">:</span> <span class="n">autoCxl</span><span class="p">,</span>
              <span class="s1">&#39;clOrdId&#39;</span><span class="p">:</span> <span class="n">clOrdId</span><span class="p">,</span> <span class="s1">&#39;tag&#39;</span><span class="p">:</span> <span class="n">tag</span><span class="p">}</span>
    <span class="kn">from</span> <span class="nn">pyokx.low_rest_api.consts</span> <span class="kn">import</span> <span class="n">CLOSE_POSITION</span>
    <span class="kn">from</span> <span class="nn">pyokx.low_rest_api.consts</span> <span class="kn">import</span> <span class="n">POST</span>
    <span class="n">closed_position_return</span> <span class="o">=</span> <span class="n">tradeAPI</span><span class="o">.</span><span class="n">_request_with_params</span><span class="p">(</span><span class="n">POST</span><span class="p">,</span> <span class="n">CLOSE_POSITION</span><span class="p">,</span> <span class="n">params</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">closed_position_return</span></div>



<div class="viewcode-block" id="close_all_positions">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.close_all_positions">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">close_all_positions</span><span class="p">(</span><span class="n">positions_list</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">Position</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">instType</span><span class="p">:</span> <span class="n">InstType</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">instId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Closes all or specific positions based on the provided parameters.</span>

<span class="sd">    :param positions_list: A list of specific positions to close. If not provided, all positions are closed.</span>
<span class="sd">    :type positions_list: List[Position], optional</span>
<span class="sd">    :param instType: The type of instrument to close positions for.</span>
<span class="sd">    :type instType: InstType, optional</span>
<span class="sd">    :param instId: The specific instrument ID to close positions for.</span>
<span class="sd">    :type instId: str, optional</span>
<span class="sd">    :returns: A list of the positions that were successfully closed.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">positions_list</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">params</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">if</span> <span class="n">instType</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instType&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instType</span>
        <span class="k">if</span> <span class="n">instId</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instId&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instId</span>
        <span class="n">positions_list</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_all_positions</span><span class="p">(</span><span class="o">**</span><span class="n">params</span><span class="p">)</span>

    <span class="n">closed_positions_return</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span>
        <span class="o">*</span><span class="p">[</span><span class="n">close_position</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">position</span><span class="o">.</span><span class="n">instId</span><span class="p">,</span> <span class="n">mgnMode</span><span class="o">=</span><span class="n">position</span><span class="o">.</span><span class="n">mgnMode</span><span class="p">,</span>
                         <span class="n">posSide</span><span class="o">=</span><span class="n">position</span><span class="o">.</span><span class="n">posSide</span><span class="p">,</span> <span class="n">ccy</span><span class="o">=</span><span class="n">position</span><span class="o">.</span><span class="n">ccy</span><span class="p">,</span>
                         <span class="n">autoCxl</span><span class="o">=</span><span class="s1">&#39;true&#39;</span><span class="p">,</span> <span class="n">clOrdId</span><span class="o">=</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">position</span><span class="o">.</span><span class="n">posId</span><span class="si">}</span><span class="s1">CLOSED&#39;</span><span class="p">,</span>
                         <span class="n">tag</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="k">for</span> <span class="n">position</span> <span class="ow">in</span> <span class="n">positions_list</span><span class="p">]</span>
    <span class="p">)</span>

    <span class="n">closed_positions</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">closed_position</span> <span class="ow">in</span> <span class="n">closed_positions_return</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">assert</span> <span class="n">closed_position</span><span class="p">[</span><span class="s1">&#39;code&#39;</span><span class="p">]</span> <span class="o">==</span> <span class="s1">&#39;0&#39;</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39; </span><span class="si">{</span><span class="n">closed_position</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
            <span class="n">closed_position</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_request_data</span><span class="p">(</span><span class="n">closed_position</span><span class="p">,</span> <span class="n">Closed_Position</span><span class="p">)</span>
            <span class="n">closed_positions</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">closed_position</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
        <span class="k">except</span> <span class="ne">AssertionError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
            <span class="nb">print</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">closed_positions</span></div>



<div class="viewcode-block" id="get_all_positions">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_all_positions">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_all_positions</span><span class="p">(</span><span class="n">instType</span><span class="p">:</span> <span class="n">InstType</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">instId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Fetches all positions matching the given criteria from the account API.</span>

<span class="sd">    :param instType: The type of instrument to fetch positions for (e.g., &#39;FUTURES&#39;).</span>
<span class="sd">    :type instType: InstType, optional</span>
<span class="sd">    :param instId: The specific instrument ID to fetch positions for.</span>
<span class="sd">    :type instId: str, optional</span>
<span class="sd">    :returns: A list of positions that match the given criteria.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">params</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="k">if</span> <span class="n">instType</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instType&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instType</span>
    <span class="k">if</span> <span class="n">instId</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instId&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instId</span>
    <span class="k">return</span> <span class="k">await</span> <span class="n">get_request_data</span><span class="p">(</span><span class="n">accountAPI</span><span class="o">.</span><span class="n">get_positions</span><span class="p">(</span><span class="o">**</span><span class="n">params</span><span class="p">),</span> <span class="n">Position</span><span class="p">)</span></div>



<div class="viewcode-block" id="place_order">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.place_order">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">place_order</span><span class="p">(</span><span class="n">instId</span><span class="p">:</span> <span class="n">Any</span><span class="p">,</span>
                      <span class="n">tdMode</span><span class="p">:</span> <span class="n">Any</span><span class="p">,</span>
                      <span class="n">side</span><span class="p">:</span> <span class="n">Any</span><span class="p">,</span>
                      <span class="n">ordType</span><span class="p">:</span> <span class="n">Any</span><span class="p">,</span>
                      <span class="n">sz</span><span class="p">:</span> <span class="n">Any</span><span class="p">,</span>
                      <span class="n">ccy</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">clOrdId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">tag</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">posSide</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">px</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">reduceOnly</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">tgtCcy</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">tpTriggerPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">tpOrdPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">slTriggerPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">slOrdPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">tpTriggerPxType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">slTriggerPxType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">quickMgnType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">stpId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">stpMode</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="n">algoClOrdId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
                      <span class="c1"># This one is commented out because it needs multiple TP&#39;s to work and is not</span>
                      <span class="c1"># developed yet downstream</span>
                      <span class="c1"># amendPxOnTriggerType: str = &#39;&#39;</span>
                      <span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Places an order with the specified parameters.</span>

<span class="sd">    :param instId: The instrument ID for the order.</span>
<span class="sd">    :type instId: Any</span>
<span class="sd">    :param tdMode: The trade mode for the order (e.g., &#39;cash&#39;, &#39;margin&#39;).</span>
<span class="sd">    :type tdMode: Any</span>
<span class="sd">    :param side: The side of the order (&#39;buy&#39; or &#39;sell&#39;).</span>
<span class="sd">    :type side: Any</span>
<span class="sd">    :param ordType: The type of the order (e.g., &#39;limit&#39;, &#39;market&#39;).</span>
<span class="sd">    :type ordType: Any</span>
<span class="sd">    :param sz: The size of the order.</span>
<span class="sd">    :type sz: Any</span>
<span class="sd">    ... (and so on for other parameters)</span>
<span class="sd">    :returns: The response from the order placement request.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">tradeAPI</span><span class="o">.</span><span class="n">place_order</span><span class="p">(</span>
        <span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span> <span class="n">tdMode</span><span class="o">=</span><span class="n">tdMode</span><span class="p">,</span> <span class="n">side</span><span class="o">=</span><span class="n">side</span><span class="p">,</span> <span class="n">ordType</span><span class="o">=</span><span class="n">ordType</span><span class="p">,</span> <span class="n">sz</span><span class="o">=</span><span class="n">sz</span><span class="p">,</span>
        <span class="n">ccy</span><span class="o">=</span><span class="n">ccy</span><span class="p">,</span> <span class="n">clOrdId</span><span class="o">=</span><span class="n">clOrdId</span><span class="p">,</span> <span class="n">tag</span><span class="o">=</span><span class="n">tag</span><span class="p">,</span> <span class="n">posSide</span><span class="o">=</span><span class="n">posSide</span><span class="p">,</span>
        <span class="n">px</span><span class="o">=</span><span class="n">px</span><span class="p">,</span> <span class="n">reduceOnly</span><span class="o">=</span><span class="n">reduceOnly</span><span class="p">,</span> <span class="n">tgtCcy</span><span class="o">=</span><span class="n">tgtCcy</span><span class="p">,</span>
        <span class="n">tpTriggerPx</span><span class="o">=</span><span class="n">tpTriggerPx</span><span class="p">,</span> <span class="n">tpOrdPx</span><span class="o">=</span><span class="n">tpOrdPx</span><span class="p">,</span>
        <span class="n">slTriggerPx</span><span class="o">=</span><span class="n">slTriggerPx</span><span class="p">,</span> <span class="n">slOrdPx</span><span class="o">=</span><span class="n">slOrdPx</span><span class="p">,</span>
        <span class="n">tpTriggerPxType</span><span class="o">=</span><span class="n">tpTriggerPxType</span><span class="p">,</span> <span class="n">slTriggerPxType</span><span class="o">=</span><span class="n">slTriggerPxType</span><span class="p">,</span>
        <span class="n">quickMgnType</span><span class="o">=</span><span class="n">quickMgnType</span><span class="p">,</span> <span class="n">stpId</span><span class="o">=</span><span class="n">stpId</span><span class="p">,</span> <span class="n">stpMode</span><span class="o">=</span><span class="n">stpMode</span><span class="p">,</span>
        <span class="n">algoClOrdId</span><span class="o">=</span><span class="n">algoClOrdId</span><span class="p">,</span>
        <span class="c1"># This one is commented out because it needs multiple TP&#39;s to work and is not</span>
        <span class="c1"># developed yet downstream</span>
        <span class="c1"># amendPxOnTriggerType=amendPxOnTriggerType,</span>

    <span class="p">)</span>

    <span class="k">if</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="s2">&quot;0&quot;</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">result</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Unsuccessful order request，</span><span class="se">\n</span><span class="s2">  error_code = &quot;</span><span class="p">,</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">],</span> <span class="s2">&quot;, </span><span class="se">\n</span><span class="s2">  Error_message = &quot;</span><span class="p">,</span>
              <span class="n">result</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">])</span>
        <span class="k">return</span> <span class="kc">None</span>

    <span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_request_data</span><span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="n">Order_Placement_Return</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">result</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span></div>



<div class="viewcode-block" id="get_ticker">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_ticker">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_ticker</span><span class="p">(</span><span class="n">instId</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Retrieves the latest ticker information for a specified instrument.</span>

<span class="sd">    :param instId: The instrument ID for which to get the ticker information.</span>
<span class="sd">    :type instId: str</span>
<span class="sd">    :returns: The latest ticker information for the specified instrument.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_request_data</span><span class="p">(</span><span class="n">marketAPI</span><span class="o">.</span><span class="n">get_ticker</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">),</span> <span class="n">Ticker</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">result</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">result</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="kc">None</span></div>



<div class="viewcode-block" id="get_all_algo_orders">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_all_algo_orders">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_all_algo_orders</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">ordType</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Fetches all algorithmic orders matching the given criteria from the trading API.</span>

<span class="sd">    :param instId: The specific instrument ID to fetch algo orders for, defaults to </span>
<span class="sd">    :type instId: str, optional</span>
<span class="sd">    :param ordType: The type of algo order (e.g., &#39;trigger&#39;, &#39;oco&#39;), defaults to </span>
<span class="sd">    :type ordType: str, optional</span>
<span class="sd">    :returns: A list of algo orders that match the given criteria.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">ordType</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">ORDER_TYPES_TO_TRY</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;trigger&#39;</span><span class="p">,</span> <span class="s1">&#39;oco&#39;</span><span class="p">,</span> <span class="s1">&#39;conditional&#39;</span><span class="p">,</span> <span class="s1">&#39;move_order_stop&#39;</span><span class="p">,</span> <span class="s1">&#39;twap&#39;</span><span class="p">]</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">ORDER_TYPES_TO_TRY</span> <span class="o">=</span> <span class="p">[</span><span class="n">ordType</span><span class="p">]</span>

    <span class="c1"># orders_fetched = []</span>

    <span class="n">algo_type_to_fetch_params</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">ordType</span> <span class="ow">in</span> <span class="n">ORDER_TYPES_TO_TRY</span><span class="p">:</span>
        <span class="n">params</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;ordType&#39;</span><span class="p">:</span> <span class="n">ordType</span><span class="p">}</span>
        <span class="k">if</span> <span class="n">instId</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instId&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instId</span>

        <span class="n">algo_type_to_fetch_params</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">params</span><span class="p">)</span>

    <span class="n">orders_fetched_list</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span>
        <span class="o">*</span><span class="p">[</span><span class="n">get_request_data</span><span class="p">(</span>
            <span class="n">tradeAPI</span><span class="o">.</span><span class="n">order_algos_list</span><span class="p">(</span><span class="o">**</span><span class="n">params</span><span class="p">),</span> <span class="n">Algo_Order</span><span class="p">)</span> <span class="k">for</span> <span class="n">params</span> <span class="ow">in</span> <span class="n">algo_type_to_fetch_params</span><span class="p">]</span>
    <span class="p">)</span>

    <span class="n">orders_fetched</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">order_types</span> <span class="ow">in</span> <span class="n">orders_fetched_list</span><span class="p">:</span>
        <span class="n">orders_fetched</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">order_types</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">orders_fetched</span></div>



<div class="viewcode-block" id="cancel_all_algo_orders_with_params">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.cancel_all_algo_orders_with_params">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">cancel_all_algo_orders_with_params</span><span class="p">(</span><span class="n">algo_orders_list</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">Algo_Order</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">instId</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">ordType</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Cancels all or specific algorithmic orders based on the provided parameters.</span>

<span class="sd">    :param algo_orders_list: A list of specific algo orders to cancel. If not provided, all algo orders are cancelled.</span>
<span class="sd">    :type algo_orders_list: List[Algo_Order], optional</span>
<span class="sd">    :param instId: The specific instrument ID to cancel algo orders for, defaults to </span>
<span class="sd">    :type instId: str, optional</span>
<span class="sd">    :param ordType: The type of algo order (e.g., &#39;trigger&#39;, &#39;oco&#39;), defaults to </span>
<span class="sd">    :type ordType: str, optional</span>
<span class="sd">    :returns: A list of the algo orders that were successfully cancelled.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">assert</span> <span class="n">algo_orders_list</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">or</span> <span class="p">(</span>
            <span class="n">instId</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">or</span> <span class="n">ordType</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">),</span> <span class="sa">f</span><span class="s1">&#39;algo_orders_list or instId must be provided&#39;</span>

    <span class="k">if</span> <span class="n">algo_orders_list</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">and</span> <span class="p">(</span><span class="n">instId</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">or</span> <span class="n">ordType</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">):</span>
        <span class="n">params</span> <span class="o">=</span> <span class="p">{}</span>
        <span class="k">if</span> <span class="n">instId</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">params</span><span class="p">[</span><span class="s1">&#39;instId&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">instId</span>
        <span class="k">if</span> <span class="n">ordType</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">params</span><span class="p">[</span><span class="s1">&#39;ordType&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">ordType</span>
        <span class="n">algo_orders_list</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_all_algo_orders</span><span class="p">(</span><span class="o">**</span><span class="n">params</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">algo_orders_list</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">or</span> <span class="nb">len</span><span class="p">(</span><span class="n">algo_orders_list</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">return</span> <span class="p">[]</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">tradeAPI</span><span class="o">.</span><span class="n">cancel_algo_order</span><span class="p">(</span>
        <span class="n">params</span><span class="o">=</span><span class="p">[</span>
            <span class="p">{</span><span class="s1">&#39;algoId&#39;</span><span class="p">:</span> <span class="n">algo_order</span><span class="o">.</span><span class="n">algoId</span><span class="p">,</span>
             <span class="s1">&#39;instId&#39;</span><span class="p">:</span> <span class="n">algo_order</span><span class="o">.</span><span class="n">instId</span><span class="p">,</span>
             <span class="p">}</span> <span class="k">for</span> <span class="n">algo_order</span> <span class="ow">in</span> <span class="n">algo_orders_list</span>
        <span class="p">]</span>
    <span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">result</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">await</span> <span class="n">get_request_data</span><span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="n">Cancelled_Algo_Order</span><span class="p">)</span></div>



<div class="viewcode-block" id="place_algo_order">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.place_algo_order">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">place_algo_order</span><span class="p">(</span>
        <span class="n">instId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">tdMode</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">side</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">ordType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">sz</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">ccy</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">posSide</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">reduceOnly</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">tpTriggerPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">tpOrdPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">slTriggerPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">slOrdPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">triggerPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">orderPx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">tgtCcy</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">pxVar</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">pxSpread</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">szLimit</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">pxLimit</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">timeInterval</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">tpTriggerPxType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">slTriggerPxType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">callbackRatio</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">callbackSpread</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">activePx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">tag</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">triggerPxType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">closeFraction</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">quickMgnType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">algoClOrdId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">cxlOnClosePos</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
<span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Places an algorithmic order with detailed parameters.</span>
<span class="sd">    (as defined by the OKX API documentation, see Orders vs Algo Orders for more details)</span>

<span class="sd">    :param instId: The instrument ID for the order.</span>
<span class="sd">    :type instId: str</span>
<span class="sd">    :param tdMode: The trade mode for the order (e.g., &#39;cash&#39;, &#39;margin&#39;).</span>
<span class="sd">    :type tdMode: str</span>
<span class="sd">    ... (and so on for other parameters)</span>
<span class="sd">    :returns: The response from the algorithmic order placement request.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">tradeAPI</span><span class="o">.</span><span class="n">place_algo_order</span><span class="p">(</span>
        <span class="c1"># Main Order with TP and SL</span>
        <span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span>
        <span class="n">tdMode</span><span class="o">=</span><span class="n">tdMode</span><span class="p">,</span>
        <span class="n">side</span><span class="o">=</span><span class="n">side</span><span class="p">,</span>
        <span class="n">ordType</span><span class="o">=</span><span class="n">ordType</span><span class="p">,</span>
        <span class="n">sz</span><span class="o">=</span><span class="n">sz</span><span class="p">,</span>
        <span class="n">ccy</span><span class="o">=</span><span class="n">ccy</span><span class="p">,</span>
        <span class="n">posSide</span><span class="o">=</span><span class="n">posSide</span><span class="p">,</span>
        <span class="n">reduceOnly</span><span class="o">=</span><span class="n">reduceOnly</span><span class="p">,</span>
        <span class="n">tpTriggerPx</span><span class="o">=</span><span class="n">tpTriggerPx</span><span class="p">,</span> <span class="n">tpOrdPx</span><span class="o">=</span><span class="n">tpOrdPx</span><span class="p">,</span> <span class="n">slTriggerPx</span><span class="o">=</span><span class="n">slTriggerPx</span><span class="p">,</span> <span class="n">slOrdPx</span><span class="o">=</span><span class="n">slOrdPx</span><span class="p">,</span> <span class="n">triggerPx</span><span class="o">=</span><span class="n">triggerPx</span><span class="p">,</span>
        <span class="n">orderPx</span><span class="o">=</span><span class="n">orderPx</span><span class="p">,</span> <span class="n">tgtCcy</span><span class="o">=</span><span class="n">tgtCcy</span><span class="p">,</span> <span class="n">pxVar</span><span class="o">=</span><span class="n">pxVar</span><span class="p">,</span> <span class="n">pxSpread</span><span class="o">=</span><span class="n">pxSpread</span><span class="p">,</span> <span class="n">szLimit</span><span class="o">=</span><span class="n">szLimit</span><span class="p">,</span> <span class="n">pxLimit</span><span class="o">=</span><span class="n">pxLimit</span><span class="p">,</span>
        <span class="n">timeInterval</span><span class="o">=</span><span class="n">timeInterval</span><span class="p">,</span> <span class="n">tpTriggerPxType</span><span class="o">=</span><span class="n">tpTriggerPxType</span><span class="p">,</span> <span class="n">slTriggerPxType</span><span class="o">=</span><span class="n">slTriggerPxType</span><span class="p">,</span>
        <span class="n">callbackRatio</span><span class="o">=</span><span class="n">callbackRatio</span><span class="p">,</span> <span class="n">callbackSpread</span><span class="o">=</span><span class="n">callbackSpread</span><span class="p">,</span> <span class="n">activePx</span><span class="o">=</span><span class="n">activePx</span><span class="p">,</span> <span class="n">tag</span><span class="o">=</span><span class="n">tag</span><span class="p">,</span>
        <span class="n">triggerPxType</span><span class="o">=</span><span class="n">triggerPxType</span><span class="p">,</span> <span class="n">closeFraction</span><span class="o">=</span><span class="n">closeFraction</span><span class="p">,</span> <span class="n">quickMgnType</span><span class="o">=</span><span class="n">quickMgnType</span><span class="p">,</span> <span class="n">algoClOrdId</span><span class="o">=</span><span class="n">algoClOrdId</span><span class="p">,</span>
        <span class="n">cxlOnClosePos</span><span class="o">=</span><span class="n">cxlOnClosePos</span>
    <span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">result</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="s2">&quot;0&quot;</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">result</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Unsuccessful algo order request，</span><span class="se">\n</span><span class="s2">  error_code = &quot;</span><span class="p">,</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">],</span> <span class="s2">&quot;, </span><span class="se">\n</span><span class="s2">  Error_message = &quot;</span><span class="p">,</span>
              <span class="n">result</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">])</span>

    <span class="k">return</span> <span class="k">await</span> <span class="n">get_request_data</span><span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="n">Algo_Order_Placement_Return</span><span class="p">)</span></div>



<div class="viewcode-block" id="get_account_balance">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_account_balance">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_account_balance</span><span class="p">():</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Retrieves the account balance details.</span>

<span class="sd">    :returns: The account balance data, structured according to the AccountBalanceData class.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">account_balance</span> <span class="o">=</span> <span class="n">accountAPI</span><span class="o">.</span><span class="n">get_account_balance</span><span class="p">()[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span>
    <span class="n">details</span> <span class="o">=</span> <span class="n">account_balance</span><span class="p">[</span><span class="s1">&#39;details&#39;</span><span class="p">]</span>
    <span class="n">structured_details</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">detail</span> <span class="ow">in</span> <span class="n">details</span><span class="p">:</span>
        <span class="n">structured_details</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">AccountBalanceDetails</span><span class="p">(</span><span class="o">**</span><span class="n">detail</span><span class="p">))</span>
    <span class="n">account_balance</span><span class="p">[</span><span class="s1">&#39;details&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">structured_details</span>
    <span class="k">return</span> <span class="n">AccountBalanceData</span><span class="p">(</span><span class="o">**</span><span class="n">account_balance</span><span class="p">)</span></div>



<div class="viewcode-block" id="get_account_config">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_account_config">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_account_config</span><span class="p">():</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Retrieves the account configuration details.</span>

<span class="sd">    :returns: The account configuration data, structured according to the AccountConfigData class.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">AccountConfigData</span><span class="p">(</span><span class="o">**</span><span class="n">accountAPI</span><span class="o">.</span><span class="n">get_account_config</span><span class="p">()[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">])</span></div>



<div class="viewcode-block" id="get_max_order_size">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_max_order_size">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_max_order_size</span><span class="p">(</span><span class="n">instId</span><span class="p">,</span> <span class="n">tdMode</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Retrieves the maximum order size for a specific instrument and trade mode.</span>

<span class="sd">    :param instId: The instrument ID for which to get the maximum order size.</span>
<span class="sd">    :type instId: str</span>
<span class="sd">    :param tdMode: The trade mode (e.g., &#39;cash&#39;, &#39;margin&#39;).</span>
<span class="sd">    :type tdMode: str</span>
<span class="sd">    :returns: The maximum order size data, structured according to the MaxOrderSizeData class.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="c1"># return MaxOrderSizeData(**accountAPI.get_max_order_size(instId=instId, tdMode=tdMode)[&#39;data&#39;][0])</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">accountAPI</span><span class="o">.</span><span class="n">get_max_order_size</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span> <span class="n">tdMode</span><span class="o">=</span><span class="n">tdMode</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="s2">&quot;0&quot;</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Unsuccessful get_max_order_size request，</span><span class="se">\n</span><span class="s2">  error_code = &quot;</span><span class="p">,</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">],</span> <span class="s2">&quot;, </span><span class="se">\n</span><span class="s2">  Error_message = &quot;</span><span class="p">,</span>
              <span class="n">result</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">])</span>
        <span class="k">return</span> <span class="p">[]</span>
    <span class="k">return</span> <span class="n">MaxOrderSizeData</span><span class="p">(</span><span class="o">**</span><span class="n">result</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">])</span></div>



<div class="viewcode-block" id="get_max_avail_size">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_max_avail_size">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_max_avail_size</span><span class="p">(</span><span class="n">instId</span><span class="p">,</span> <span class="n">tdMode</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Retrieves the maximum available size for trading a specific instrument in a specific trade mode.</span>

<span class="sd">    :param instId: The instrument ID for which to get the maximum available size.</span>
<span class="sd">    :type instId: str</span>
<span class="sd">    :param tdMode: The trade mode (e.g., &#39;cash&#39;, &#39;margin&#39;).</span>
<span class="sd">    :type tdMode: str</span>
<span class="sd">    :returns: The maximum available size data, structured according to the MaxAvailSizeData class.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="c1"># return MaxAvailSizeData(**accountAPI.get_max_avail_size(instId=instId, tdMode=tdMode)[&#39;data&#39;][0])</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">accountAPI</span><span class="o">.</span><span class="n">get_max_avail_size</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span> <span class="n">tdMode</span><span class="o">=</span><span class="n">tdMode</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="s2">&quot;0&quot;</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Unsuccessful get_max_avail_size request，</span><span class="se">\n</span><span class="s2">  error_code = &quot;</span><span class="p">,</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">],</span> <span class="s2">&quot;, </span><span class="se">\n</span><span class="s2">  Error_message = &quot;</span><span class="p">,</span>
              <span class="n">result</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">])</span>
        <span class="k">return</span> <span class="p">[]</span>
    <span class="k">return</span> <span class="n">MaxAvailSizeData</span><span class="p">(</span><span class="o">**</span><span class="n">result</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">])</span></div>



<div class="viewcode-block" id="generate_random_string">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.generate_random_string">[docs]</a>
<span class="k">def</span> <span class="nf">generate_random_string</span><span class="p">(</span><span class="n">length</span><span class="p">,</span> <span class="n">char_type</span><span class="o">=</span><span class="s1">&#39;alphanumeric&#39;</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Generates a random string of the specified length and character type.</span>

<span class="sd">    :param length: The length of the random string to generate.</span>
<span class="sd">    :type length: int</span>
<span class="sd">    :param char_type: The type of characters to include in the string (&#39;alphanumeric&#39;, &#39;numeric&#39;, or &#39;alphabetic&#39;).</span>
<span class="sd">                      Defaults to &#39;alphanumeric&#39;.</span>
<span class="sd">    :type char_type: str, optional</span>
<span class="sd">    :returns: A random string of the specified length and character type.</span>
<span class="sd">    :raises ValueError: If the length exceeds 32 or if an invalid char_type is specified.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">length</span> <span class="o">&gt;</span> <span class="mi">32</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Maximum length allowed is 32&quot;</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">char_type</span> <span class="o">==</span> <span class="s1">&#39;alphanumeric&#39;</span><span class="p">:</span>
        <span class="n">char_set</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">ascii_letters</span> <span class="o">+</span> <span class="n">string</span><span class="o">.</span><span class="n">digits</span>
    <span class="k">elif</span> <span class="n">char_type</span> <span class="o">==</span> <span class="s1">&#39;numeric&#39;</span><span class="p">:</span>
        <span class="n">char_set</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">digits</span>
    <span class="k">elif</span> <span class="n">char_type</span> <span class="o">==</span> <span class="s1">&#39;alphabetic&#39;</span><span class="p">:</span>
        <span class="n">char_set</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">ascii_letters</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Invalid character type. Choose &#39;alphanumeric&#39;, &#39;numeric&#39;, or &#39;alphabetic&#39;.&quot;</span><span class="p">)</span>

    <span class="k">return</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">choices</span><span class="p">(</span><span class="n">char_set</span><span class="p">,</span> <span class="n">k</span><span class="o">=</span><span class="n">length</span><span class="p">))</span></div>



<div class="viewcode-block" id="fetch_status_report_for_instrument">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.fetch_status_report_for_instrument">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">fetch_status_report_for_instrument</span><span class="p">(</span><span class="n">instId</span><span class="p">,</span> <span class="n">TD_MODE</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Fetches a comprehensive status report for a specific instrument.</span>

<span class="sd">    :param instId: The instrument ID for which to fetch the status report.</span>
<span class="sd">    :type instId: str</span>
<span class="sd">    :param TD_MODE: The trade mode (e.g., &#39;cash&#39;, &#39;margin&#39;).</span>
<span class="sd">    :type TD_MODE: str</span>
<span class="sd">    :returns: A status report for the instrument, structured according to the InstrumentStatusReport class.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="c1"># Handle the case where instId is None</span>
    <span class="k">if</span> <span class="n">instId</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="kc">None</span>

    <span class="p">(</span><span class="n">max_order_size</span><span class="p">,</span> <span class="n">max_avail_size</span><span class="p">,</span>
     <span class="n">all_positions</span><span class="p">,</span> <span class="n">all_orders</span><span class="p">,</span> <span class="n">all_algo_orders</span><span class="p">)</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span>
        <span class="n">get_max_order_size</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span> <span class="n">tdMode</span><span class="o">=</span><span class="n">TD_MODE</span><span class="p">),</span>
        <span class="n">get_max_avail_size</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span> <span class="n">tdMode</span><span class="o">=</span><span class="n">TD_MODE</span><span class="p">),</span>
        <span class="n">get_all_positions</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">),</span>
        <span class="n">get_all_orders</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">),</span>
        <span class="n">get_all_algo_orders</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">)</span>
    <span class="p">)</span>
    <span class="k">return</span> <span class="n">InstrumentStatusReport</span><span class="p">(</span>
        <span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span>
        <span class="n">max_order_size</span><span class="o">=</span><span class="n">max_order_size</span><span class="p">,</span>
        <span class="n">max_avail_size</span><span class="o">=</span><span class="n">max_avail_size</span><span class="p">,</span>
        <span class="n">positions</span><span class="o">=</span><span class="n">all_positions</span><span class="p">,</span>
        <span class="n">orders</span><span class="o">=</span><span class="n">all_orders</span><span class="p">,</span>
        <span class="n">algo_orders</span><span class="o">=</span><span class="n">all_algo_orders</span>
    <span class="p">)</span></div>



<div class="viewcode-block" id="fetch_initial_data">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.fetch_initial_data">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">fetch_initial_data</span><span class="p">(</span><span class="n">TD_MODE</span><span class="p">,</span> <span class="n">instId</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Fetches initial data including account balance, account configuration, and instrument status.</span>

<span class="sd">    :param TD_MODE: The trade mode (e.g., &#39;cash&#39;, &#39;margin&#39;).</span>
<span class="sd">    :type TD_MODE: str</span>
<span class="sd">    :param instId: The instrument ID for which to fetch the data, defaults to </span>
<span class="sd">    :type instId: str, optional</span>
<span class="sd">    :returns: A tuple containing simplified balance details, account configuration data, and instrument status report.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">account_balance</span><span class="p">,</span> <span class="n">account_config</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span><span class="n">get_account_balance</span><span class="p">(),</span> <span class="n">get_account_config</span><span class="p">())</span>

    <span class="n">simplified_balance_details</span> <span class="o">=</span> <span class="p">[</span>
        <span class="n">Simplified_Balance_Details</span><span class="p">(</span>
            <span class="n">Currency</span><span class="o">=</span><span class="n">detail</span><span class="o">.</span><span class="n">ccy</span><span class="p">,</span>
            <span class="n">Available_Balance</span><span class="o">=</span><span class="n">detail</span><span class="o">.</span><span class="n">availBal</span><span class="p">,</span>
            <span class="n">Equity</span><span class="o">=</span><span class="n">detail</span><span class="o">.</span><span class="n">eq</span><span class="p">,</span>
            <span class="n">Equity_in_USD</span><span class="o">=</span><span class="n">detail</span><span class="o">.</span><span class="n">eqUsd</span><span class="p">,</span>
            <span class="n">Frozen_Balance</span><span class="o">=</span><span class="n">detail</span><span class="o">.</span><span class="n">frozenBal</span><span class="p">,</span>
        <span class="p">)</span>
        <span class="k">for</span> <span class="n">detail</span> <span class="ow">in</span> <span class="n">account_balance</span><span class="o">.</span><span class="n">details</span>
    <span class="p">]</span>

    <span class="n">instrument_status_report</span> <span class="o">=</span> <span class="k">await</span> <span class="n">fetch_status_report_for_instrument</span><span class="p">(</span><span class="n">instId</span><span class="p">,</span> <span class="n">TD_MODE</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">simplified_balance_details</span><span class="p">,</span> <span class="n">account_config</span><span class="p">,</span> <span class="n">instrument_status_report</span></div>



<div class="viewcode-block" id="clear_orders_and_positions_for_instrument">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.clear_orders_and_positions_for_instrument">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">clear_orders_and_positions_for_instrument</span><span class="p">(</span><span class="n">instId</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Clears all orders and positions for a specific instrument.</span>

<span class="sd">    :param instId: The instrument ID for which to clear orders and positions.</span>
<span class="sd">    :type instId: str</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">closed_positions</span> <span class="o">=</span> <span class="k">await</span> <span class="n">close_all_positions</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">)</span>
    <span class="n">cancelled_orders</span> <span class="o">=</span> <span class="k">await</span> <span class="n">cancel_all_orders</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">)</span>
    <span class="n">cancelled_algo_orders</span> <span class="o">=</span> <span class="k">await</span> <span class="n">cancel_all_algo_orders_with_params</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">closed_positions</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">cancelled_orders</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">cancelled_algo_orders</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span></div>



<div class="viewcode-block" id="get_order_book">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_order_book">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_order_book</span><span class="p">(</span><span class="n">instId</span><span class="p">,</span> <span class="n">depth</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Fetches the order book for a specific instrument.</span>

<span class="sd">    :param instId: The instrument ID for which to get the order book.</span>
<span class="sd">    :type instId: str</span>
<span class="sd">    :param depth: The depth of the order book to fetch.</span>
<span class="sd">    :type depth: int</span>
<span class="sd">    :returns: The order book snapshot, structured according to the Orderbook_Snapshot class.</span>
<span class="sd">    :raises ValueError: If the order book could not be fetched for the specified instrument ID.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">orderbook_return</span> <span class="o">=</span> <span class="n">marketAPI</span><span class="o">.</span><span class="n">get_orderbook</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span> <span class="n">sz</span><span class="o">=</span><span class="n">depth</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">orderbook_return</span><span class="p">[</span><span class="s1">&#39;code&#39;</span><span class="p">]</span> <span class="o">!=</span> <span class="s1">&#39;0&#39;</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">orderbook_return</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Could not fetch orderbook for </span><span class="si">{</span><span class="n">instId</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">orderbook_return</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span>
    <span class="n">asks</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="s1">&#39;asks&#39;</span><span class="p">]</span>
    <span class="n">bids</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="s1">&#39;bids&#39;</span><span class="p">]</span>
    <span class="n">ts</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="s1">&#39;ts&#39;</span><span class="p">]</span>
    <span class="n">structured_asks</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">structured_bids</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="k">for</span> <span class="n">ask</span><span class="p">,</span> <span class="n">bid</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">asks</span><span class="p">,</span> <span class="n">bids</span><span class="p">):</span>
        <span class="n">structured_asks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">Ask</span><span class="p">(</span><span class="n">price</span><span class="o">=</span><span class="n">ask</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">quantity</span><span class="o">=</span><span class="n">ask</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">deprecated_value</span><span class="o">=</span><span class="n">ask</span><span class="p">[</span><span class="mi">2</span><span class="p">],</span> <span class="n">number_of_orders</span><span class="o">=</span><span class="n">ask</span><span class="p">[</span><span class="mi">3</span><span class="p">]))</span>
        <span class="n">structured_bids</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">Bid</span><span class="p">(</span><span class="n">price</span><span class="o">=</span><span class="n">bid</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">quantity</span><span class="o">=</span><span class="n">bid</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">deprecated_value</span><span class="o">=</span><span class="n">bid</span><span class="p">[</span><span class="mi">2</span><span class="p">],</span> <span class="n">number_of_orders</span><span class="o">=</span><span class="n">bid</span><span class="p">[</span><span class="mi">3</span><span class="p">]))</span>

    <span class="k">return</span> <span class="n">Orderbook_Snapshot</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span> <span class="n">depth</span><span class="o">=</span><span class="nb">str</span><span class="p">(</span><span class="n">depth</span><span class="p">),</span> <span class="n">ts</span><span class="o">=</span><span class="n">ts</span><span class="p">,</span> <span class="n">asks</span><span class="o">=</span><span class="n">structured_asks</span><span class="p">,</span> <span class="n">bids</span><span class="o">=</span><span class="n">structured_bids</span><span class="p">)</span></div>



<div class="viewcode-block" id="place_algo_trailing_stop_loss">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.place_algo_trailing_stop_loss">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">place_algo_trailing_stop_loss</span><span class="p">(</span>
        <span class="n">instId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">tdMode</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">ordType</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">side</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">sz</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">activePx</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">posSide</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">callbackRatio</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">reduceOnly</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">algoClOrdId</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">cxlOnClosePos</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
<span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Places a trailing stop-loss order with detailed parameters.</span>

<span class="sd">    :param instId: The instrument ID for the order.</span>
<span class="sd">    :type instId: str</span>
<span class="sd">    :param tdMode: The trade mode for the order (e.g., &#39;cash&#39;, &#39;margin&#39;).</span>
<span class="sd">    :type tdMode: str</span>
<span class="sd">    ... (and so on for other parameters)</span>
<span class="sd">    :returns: The response from the trailing stop-loss order placement request.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">place_algo_order</span><span class="p">(</span>
        <span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span>
        <span class="n">tdMode</span><span class="o">=</span><span class="n">tdMode</span><span class="p">,</span>
        <span class="n">ordType</span><span class="o">=</span><span class="n">ordType</span><span class="p">,</span>
        <span class="n">side</span><span class="o">=</span><span class="n">side</span><span class="p">,</span>
        <span class="n">sz</span><span class="o">=</span><span class="n">sz</span><span class="p">,</span>
        <span class="n">activePx</span><span class="o">=</span><span class="n">activePx</span><span class="p">,</span>
        <span class="n">posSide</span><span class="o">=</span><span class="n">posSide</span><span class="p">,</span>
        <span class="n">callbackRatio</span><span class="o">=</span><span class="n">callbackRatio</span><span class="p">,</span>
        <span class="n">reduceOnly</span><span class="o">=</span><span class="n">reduceOnly</span><span class="p">,</span>
        <span class="n">algoClOrdId</span><span class="o">=</span><span class="n">algoClOrdId</span><span class="p">,</span>
        <span class="n">cxlOnClosePos</span><span class="o">=</span><span class="n">cxlOnClosePos</span>
    <span class="p">)</span></div>



<div class="viewcode-block" id="get_leverage">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.get_leverage">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">get_leverage</span><span class="p">(</span><span class="n">instId</span><span class="p">,</span> <span class="n">mgnMode</span><span class="p">):</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">accountAPI</span><span class="o">.</span><span class="n">get_leverage</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId</span><span class="p">,</span> <span class="n">mgnMode</span><span class="o">=</span><span class="n">mgnMode</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">]</span> <span class="o">!=</span> <span class="s2">&quot;0&quot;</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Unsuccessful get_leverage request，</span><span class="se">\n</span><span class="s2">  error_code = &quot;</span><span class="p">,</span> <span class="n">result</span><span class="p">[</span><span class="s2">&quot;code&quot;</span><span class="p">],</span> <span class="s2">&quot;, </span><span class="se">\n</span><span class="s2">  Error_message = &quot;</span><span class="p">,</span>
              <span class="n">result</span><span class="p">[</span><span class="s2">&quot;msg&quot;</span><span class="p">])</span>
        <span class="k">return</span> <span class="p">[]</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">result</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">])</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">leverage</span> <span class="o">=</span> <span class="n">result</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">][</span><span class="s1">&#39;lever&#39;</span><span class="p">]</span>
        <span class="k">return</span> <span class="nb">int</span><span class="p">(</span><span class="n">leverage</span><span class="p">)</span></div>



<div class="viewcode-block" id="prepare_limit_price">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.prepare_limit_price">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">prepare_limit_price</span><span class="p">(</span><span class="n">order_book</span><span class="p">:</span> <span class="n">Orderbook_Snapshot</span><span class="p">,</span> <span class="n">quantity</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="nb">int</span><span class="p">,</span> <span class="nb">float</span><span class="p">],</span> <span class="n">side</span><span class="p">,</span> <span class="n">reference_price</span><span class="p">:</span> <span class="nb">float</span><span class="p">,</span>
                              <span class="n">max_orderbook_price_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                              <span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Prepares a limit price based on the order book, quantity, side, reference price, and maximum order book price offset.</span>

<span class="sd">    :param order_book: The snapshot of the order book.</span>
<span class="sd">    :type order_book: Orderbook_Snapshot</span>
<span class="sd">    :param quantity: The quantity for which to prepare the limit price.</span>
<span class="sd">    :type quantity: Union[int, float]</span>
<span class="sd">    :param side: The side of the order (&#39;buy&#39; or &#39;sell&#39;).</span>
<span class="sd">    :type side: str</span>
<span class="sd">    :param reference_price: The reference price to base the limit price on.</span>
<span class="sd">    :type reference_price: float</span>
<span class="sd">    :param max_orderbook_price_offset: The maximum allowed offset from the reference price, defaults to </span>
<span class="sd">    :type max_orderbook_price_offset: float, optional</span>
<span class="sd">    :returns: The prepared limit price.</span>
<span class="sd">    :raises Exception: If a price in the order book that has enough volume to cover the quantity cannot be found.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">assert</span> <span class="n">side</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;buy&#39;</span><span class="p">,</span> <span class="s1">&#39;sell&#39;</span><span class="p">]</span>
    <span class="n">limit_price</span> <span class="o">=</span> <span class="kc">None</span>

    <span class="n">reference_side</span> <span class="o">=</span> <span class="s1">&#39;asks&#39;</span> <span class="k">if</span> <span class="n">side</span> <span class="o">==</span> <span class="s1">&#39;buy&#39;</span> <span class="k">else</span> <span class="s1">&#39;bids&#39;</span>
    <span class="n">asks_or_bids</span> <span class="o">=</span> <span class="n">order_book</span><span class="o">.</span><span class="n">asks</span> <span class="k">if</span> <span class="n">reference_side</span> <span class="o">==</span> <span class="s1">&#39;asks&#39;</span> <span class="k">else</span> <span class="n">order_book</span><span class="o">.</span><span class="n">bids</span>

    <span class="n">aggregate_quantity</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">ask_or_bid</span> <span class="ow">in</span> <span class="n">asks_or_bids</span><span class="p">:</span>
        <span class="c1"># check that if buy order then skip if reference price is greater than ask price</span>
        <span class="c1"># check that if sell order then skip if reference price is less than bid price</span>
        <span class="n">aggregate_quantity</span> <span class="o">+=</span> <span class="nb">float</span><span class="p">(</span><span class="n">ask_or_bid</span><span class="o">.</span><span class="n">quantity</span><span class="p">)</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">side</span> <span class="o">==</span> <span class="s1">&#39;buy&#39;</span> <span class="ow">and</span> <span class="n">reference_price</span> <span class="o">&gt;</span> <span class="nb">float</span><span class="p">(</span><span class="n">ask_or_bid</span><span class="o">.</span><span class="n">price</span><span class="p">))</span> <span class="ow">or</span> \
                <span class="p">(</span><span class="n">side</span> <span class="o">==</span> <span class="s1">&#39;sell&#39;</span> <span class="ow">and</span> <span class="n">reference_price</span> <span class="o">&lt;</span> <span class="nb">float</span><span class="p">(</span><span class="n">ask_or_bid</span><span class="o">.</span><span class="n">price</span><span class="p">)):</span>
            <span class="k">continue</span>

        <span class="k">if</span> <span class="n">aggregate_quantity</span> <span class="o">&gt;=</span> <span class="n">quantity</span><span class="p">:</span>
            <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;ask_or_bid_price: </span><span class="si">{</span><span class="n">ask_or_bid</span><span class="o">.</span><span class="n">price</span><span class="si">}</span><span class="s2">, ask_or_bid_volume: </span><span class="si">{</span><span class="n">ask_or_bid</span><span class="o">.</span><span class="n">quantity</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>

            <span class="c1"># Check if the price is within the range we want to place our order</span>
            <span class="c1"># get the price offset from the last price</span>
            <span class="n">price_offset</span> <span class="o">=</span> <span class="nb">abs</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">ask_or_bid</span><span class="o">.</span><span class="n">price</span><span class="p">)</span> <span class="o">-</span> <span class="nb">float</span><span class="p">(</span><span class="n">reference_price</span><span class="p">))</span> <span class="o">/</span> <span class="n">reference_price</span>
            <span class="k">if</span> <span class="p">(</span><span class="ow">not</span> <span class="n">max_orderbook_price_offset</span> <span class="ow">or</span> <span class="n">price_offset</span> <span class="o">&lt;=</span> <span class="n">max_orderbook_price_offset</span><span class="p">):</span>
                <span class="n">limit_price</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">ask_or_bid</span><span class="o">.</span><span class="n">price</span><span class="p">)</span>
                <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;</span><span class="si">{</span><span class="n">price_offset</span><span class="si">}</span><span class="s2">% diff between reference price: </span><span class="si">{</span><span class="n">reference_price</span><span class="si">}</span><span class="s2"> and and &quot;</span>
                      <span class="sa">f</span><span class="s2">&quot;limit price: </span><span class="si">{</span><span class="n">limit_price</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
                <span class="k">break</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span>
                    <span class="sa">f</span><span class="s2">&quot;Computed Limit Price </span><span class="si">{</span><span class="n">ask_or_bid</span><span class="o">.</span><span class="n">price</span><span class="si">}</span><span class="s2"> is not within the range given by&quot;</span>
                    <span class="sa">f</span><span class="s2">&quot; </span><span class="si">{</span><span class="n">max_orderbook_price_offset</span><span class="si">}</span><span class="s2">&quot;</span>
                    <span class="sa">f</span><span class="s2">&quot; if you want to remove this check, set max_orderbook_price_offset=False&quot;</span>
                <span class="p">)</span>

    <span class="k">if</span> <span class="n">limit_price</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s2">&quot;Could not find a price in the orderbook that has enough volume to cover the quantity&quot;</span><span class="p">)</span>

    <span class="k">return</span> <span class="nb">round</span><span class="p">(</span><span class="n">limit_price</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span></div>



<span class="k">async</span> <span class="k">def</span> <span class="nf">_validate_instID_and_return_ticker_info</span><span class="p">(</span><span class="n">instID</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Cleans and verifies an instrument ID to ensure it&#39;s in the correct format and exists within the list of instruments.</span>

<span class="sd">    :param instID: The instrument ID to clean and verify.</span>
<span class="sd">    :type instID: str</span>
<span class="sd">    :returns: The cleaned and verified instrument ID.</span>
<span class="sd">    :raises AssertionError: If the instrument ID is not in the correct format or the instrument is not found.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="c1"># Clean Input Data</span>
    <span class="n">instID</span> <span class="o">=</span> <span class="n">instID</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
    <span class="n">splitted</span> <span class="o">=</span> <span class="n">instID</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;-&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">splitted</span><span class="p">)</span> <span class="o">==</span> <span class="mi">3</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;The Futures instrument ID must be in the format of &quot;BTC-USDT-210326&quot;. </span><span class="si">{</span><span class="n">instID</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="n">okx_futures_instrument_searcher</span><span class="p">:</span> <span class="n">InstrumentSearcher</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_instruments_searcher_from_redis</span><span class="p">(</span>
        <span class="k">await</span> <span class="n">init_async_redis</span><span class="p">(),</span>
        <span class="n">instType</span><span class="o">=</span><span class="n">ENFORCED_INSTRUMENT_TYPE</span><span class="p">)</span>

    <span class="n">instrument</span> <span class="o">=</span> <span class="n">okx_futures_instrument_searcher</span><span class="o">.</span><span class="n">find_by_instId</span><span class="p">(</span><span class="n">instID</span><span class="p">)</span>
    <span class="k">assert</span> <span class="n">instrument</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;Instrument not found. </span><span class="si">{</span><span class="n">instID</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">return</span> <span class="n">instrument</span>


<span class="k">async</span> <span class="k">def</span> <span class="nf">_validate_okx_signal_input_tp_sl_trail_params</span><span class="p">(</span><span class="n">sl_trigger_price_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                                                        <span class="n">tp_trigger_price_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                                                        <span class="n">sl_execution_price_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">tp_execution_price_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                                                        <span class="n">trailing_stop_activation_price_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                                                        <span class="n">trailing_stop_callback_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                                                        <span class="n">max_orderbook_limit_price_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                                                        <span class="n">flip_position_if_opposite_side</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
                                                        <span class="n">tp_trigger_price_type</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">sl_trigger_price_type</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">tp_trigger_price_type</span><span class="p">:</span>
        <span class="n">tp_trigger_price_type</span> <span class="o">=</span> <span class="s1">&#39;last&#39;</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">sl_trigger_price_type</span><span class="p">:</span>
        <span class="n">sl_trigger_price_type</span> <span class="o">=</span> <span class="s1">&#39;last&#39;</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">sl_trigger_price_offset</span><span class="p">:</span>
        <span class="n">sl_trigger_price_offset</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">tp_trigger_price_offset</span><span class="p">:</span>
        <span class="n">tp_trigger_price_offset</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">sl_execution_price_offset</span><span class="p">:</span>
        <span class="n">sl_execution_price_offset</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">tp_execution_price_offset</span><span class="p">:</span>
        <span class="n">tp_execution_price_offset</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">trailing_stop_activation_price_offset</span><span class="p">:</span>
        <span class="n">trailing_stop_activation_price_offset</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">trailing_stop_callback_offset</span><span class="p">:</span>
        <span class="n">trailing_stop_callback_offset</span> <span class="o">=</span> <span class="kc">False</span>

    <span class="n">tp_trigger_price_type</span><span class="p">,</span> <span class="n">sl_trigger_price_type</span> <span class="o">=</span> <span class="n">tp_trigger_price_type</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="n">sl_trigger_price_type</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>

    <span class="n">sl_trigger_price_offset</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="p">(</span>
            <span class="n">sl_trigger_price_offset</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">sl_trigger_price_offset</span><span class="p">)</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span>
        <span class="n">sl_trigger_price_offset</span><span class="p">)</span>
    <span class="n">tp_trigger_price_offset</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="n">tp_trigger_price_offset</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">tp_trigger_price_offset</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span>
        <span class="n">tp_trigger_price_offset</span><span class="p">)</span>
    <span class="n">sl_execution_price_offset</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="n">sl_execution_price_offset</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">sl_execution_price_offset</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span>
        <span class="n">sl_execution_price_offset</span><span class="p">)</span>
    <span class="n">tp_execution_price_offset</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="n">tp_execution_price_offset</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">tp_execution_price_offset</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span>
        <span class="n">tp_execution_price_offset</span><span class="p">)</span>

    <span class="n">trailing_stop_activation_price_offset</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="n">trailing_stop_activation_price_offset</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">trailing_stop_activation_price_offset</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span>
        <span class="n">trailing_stop_activation_price_offset</span><span class="p">)</span>
    <span class="n">trailing_stop_callback_offset</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="n">trailing_stop_callback_offset</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">trailing_stop_callback_offset</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span>
        <span class="n">trailing_stop_callback_offset</span><span class="p">)</span>

    <span class="n">max_orderbook_limit_price_offset</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="n">max_orderbook_limit_price_offset</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span> <span class="ow">or</span> <span class="n">max_orderbook_limit_price_offset</span> <span class="o">==</span> <span class="mi">0</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">max_orderbook_limit_price_offset</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span>
        <span class="n">max_orderbook_limit_price_offset</span><span class="p">)</span>

    <span class="n">flip_position_if_opposite_side</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="n">flip_position_if_opposite_side</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">flip_position_if_opposite_side</span> <span class="k">else</span> <span class="nb">bool</span><span class="p">(</span>
        <span class="n">flip_position_if_opposite_side</span><span class="p">)</span>

    <span class="n">take_profit_activated</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="n">stop_loss_activated</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="n">trailing_stop_loss_activated</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="c1"># TODO multiple_tp and amendPxOnTriggerType are commented out because they need multiple TP&#39;s to work and is not</span>
    <span class="c1">#   developed yet downstream</span>
    <span class="c1">#   multiple_tp = None</span>
    <span class="c1">#   amendPxOnTriggerType = None</span>
    <span class="k">if</span> <span class="n">tp_trigger_price_offset</span> <span class="ow">or</span> <span class="n">tp_execution_price_offset</span><span class="p">:</span>
        <span class="k">assert</span> <span class="n">tp_trigger_price_offset</span> <span class="ow">and</span> <span class="n">tp_execution_price_offset</span>
        <span class="n">take_profit_activated</span> <span class="o">=</span> <span class="kc">True</span>
        <span class="n">tp_trigger_price_type</span> <span class="o">=</span> <span class="n">tp_trigger_price_type</span> <span class="ow">or</span> <span class="s1">&#39;last&#39;</span>

    <span class="k">if</span> <span class="n">sl_trigger_price_offset</span> <span class="ow">or</span> <span class="n">sl_execution_price_offset</span><span class="p">:</span>
        <span class="k">assert</span> <span class="n">sl_trigger_price_offset</span> <span class="ow">and</span> <span class="n">sl_execution_price_offset</span>
        <span class="n">stop_loss_activated</span> <span class="o">=</span> <span class="kc">True</span>
        <span class="n">sl_trigger_price_type</span> <span class="o">=</span> <span class="n">sl_trigger_price_type</span> <span class="ow">or</span> <span class="s1">&#39;last&#39;</span>

    <span class="k">if</span> <span class="n">trailing_stop_activation_price_offset</span> <span class="ow">or</span> <span class="n">trailing_stop_callback_offset</span><span class="p">:</span>
        <span class="k">assert</span> <span class="n">trailing_stop_callback_offset</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;trailing_stop_callback_offset must be provided if trailing_stop_activation_price_offset is provided. </span><span class="si">{</span><span class="n">trailing_stop_callback_offset</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
        <span class="n">trailing_stop_loss_activated</span> <span class="o">=</span> <span class="kc">True</span>

    <span class="k">assert</span> <span class="ow">not</span> <span class="n">sl_trigger_price_offset</span> <span class="ow">or</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">sl_trigger_price_offset</span><span class="p">,</span>
                                                     <span class="nb">float</span><span class="p">),</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">sl_trigger_price_offset</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">tp_trigger_price_offset</span> <span class="ow">or</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">tp_trigger_price_offset</span><span class="p">,</span>
                                                     <span class="nb">float</span><span class="p">),</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">tp_trigger_price_offset</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">sl_execution_price_offset</span> <span class="ow">or</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">sl_execution_price_offset</span><span class="p">,</span>
                                                       <span class="nb">float</span><span class="p">),</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">sl_execution_price_offset</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">tp_execution_price_offset</span> <span class="ow">or</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">tp_execution_price_offset</span><span class="p">,</span>
                                                       <span class="nb">float</span><span class="p">),</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">tp_execution_price_offset</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">sl_trigger_price_offset</span> <span class="ow">or</span> <span class="n">sl_trigger_price_offset</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">sl_trigger_price_offset</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">tp_trigger_price_offset</span> <span class="ow">or</span> <span class="n">tp_trigger_price_offset</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">tp_trigger_price_offset</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">sl_execution_price_offset</span> <span class="ow">or</span> <span class="n">sl_execution_price_offset</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">sl_execution_price_offset</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">tp_execution_price_offset</span> <span class="ow">or</span> <span class="n">tp_execution_price_offset</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">tp_execution_price_offset</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">tp_trigger_price_type</span> <span class="ow">or</span> <span class="n">tp_trigger_price_type</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;index&#39;</span><span class="p">,</span> <span class="s1">&#39;mark&#39;</span><span class="p">,</span>
                                                                  <span class="s1">&#39;last&#39;</span><span class="p">],</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">tp_trigger_price_type</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">sl_trigger_price_type</span> <span class="ow">or</span> <span class="n">sl_trigger_price_type</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;index&#39;</span><span class="p">,</span> <span class="s1">&#39;mark&#39;</span><span class="p">,</span>
                                                                  <span class="s1">&#39;last&#39;</span><span class="p">],</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">sl_trigger_price_type</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>

    <span class="k">return</span> <span class="p">{</span>
        <span class="s1">&#39;sl_trigger_price_offset&#39;</span><span class="p">:</span> <span class="n">sl_trigger_price_offset</span><span class="p">,</span>
        <span class="s1">&#39;tp_trigger_price_offset&#39;</span><span class="p">:</span> <span class="n">tp_trigger_price_offset</span><span class="p">,</span>
        <span class="s1">&#39;sl_execution_price_offset&#39;</span><span class="p">:</span> <span class="n">sl_execution_price_offset</span><span class="p">,</span>
        <span class="s1">&#39;tp_execution_price_offset&#39;</span><span class="p">:</span> <span class="n">tp_execution_price_offset</span><span class="p">,</span>
        <span class="s1">&#39;trailing_stop_activation_price_offset&#39;</span><span class="p">:</span> <span class="n">trailing_stop_activation_price_offset</span><span class="p">,</span>
        <span class="s1">&#39;trailing_stop_callback_offset&#39;</span><span class="p">:</span> <span class="n">trailing_stop_callback_offset</span><span class="p">,</span>
        <span class="s1">&#39;max_orderbook_limit_price_offset&#39;</span><span class="p">:</span> <span class="n">max_orderbook_limit_price_offset</span><span class="p">,</span>
        <span class="s1">&#39;flip_position_if_opposite_side&#39;</span><span class="p">:</span> <span class="n">flip_position_if_opposite_side</span><span class="p">,</span>
        <span class="s1">&#39;tp_trigger_price_type&#39;</span><span class="p">:</span> <span class="n">tp_trigger_price_type</span><span class="p">,</span>
        <span class="s1">&#39;sl_trigger_price_type&#39;</span><span class="p">:</span> <span class="n">sl_trigger_price_type</span><span class="p">,</span>
        <span class="s1">&#39;take_profit_activated&#39;</span><span class="p">:</span> <span class="n">take_profit_activated</span><span class="p">,</span>
        <span class="s1">&#39;stop_loss_activated&#39;</span><span class="p">:</span> <span class="n">stop_loss_activated</span><span class="p">,</span>
        <span class="s1">&#39;trailing_stop_loss_activated&#39;</span><span class="p">:</span> <span class="n">trailing_stop_loss_activated</span><span class="p">,</span>
    <span class="p">}</span>


<span class="k">async</span> <span class="k">def</span> <span class="nf">_validate_okx_signal_order_params</span><span class="p">(</span><span class="n">order_type</span><span class="p">,</span> <span class="n">order_side</span><span class="p">,</span> <span class="n">order_size</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">order_type</span><span class="p">:</span>
        <span class="n">order_type</span> <span class="o">=</span> <span class="s1">&#39;limit&#39;</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">order_side</span><span class="p">:</span>
        <span class="n">order_side</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">order_size</span><span class="p">:</span>
        <span class="n">order_size</span> <span class="o">=</span> <span class="mi">0</span>

    <span class="n">order_type</span><span class="p">,</span> <span class="n">order_side</span> <span class="o">=</span> <span class="n">order_type</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="n">order_side</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span>
    <span class="n">order_size</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">order_size</span><span class="p">)</span>
    <span class="k">assert</span> <span class="n">order_side</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;buy&#39;</span><span class="p">,</span> <span class="s1">&#39;sell&#39;</span><span class="p">]</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">order_side</span><span class="p">,</span> <span class="p">(</span>
        <span class="sa">f</span><span class="s1">&#39;order_side must be either &quot;buy&quot; or &quot;sell&quot; or empty. </span><span class="se">\n</span><span class="s1"> &#39;</span>
        <span class="sa">f</span><span class="s1">&#39;for maintenance mode </span><span class="se">\n</span><span class="s1">      </span><span class="si">{</span><span class="n">order_side</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="n">order_type</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;market&#39;</span><span class="p">,</span> <span class="s1">&#39;limit&#39;</span><span class="p">,</span> <span class="s1">&#39;post_only&#39;</span><span class="p">,</span> <span class="s1">&#39;fok&#39;</span><span class="p">,</span> <span class="s1">&#39;ioc&#39;</span><span class="p">],</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">order_type</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">order_size</span><span class="p">,</span> <span class="nb">int</span><span class="p">),</span> <span class="sa">f</span><span class="s1">&#39;Order size must be an integer/multiple of a lot size. </span><span class="si">{</span><span class="n">order_size</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="n">order_size</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;Order size must be greater than 0. </span><span class="si">{</span><span class="n">order_size</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>

    <span class="k">return</span> <span class="p">{</span>
        <span class="s1">&#39;order_type&#39;</span><span class="p">:</span> <span class="n">order_type</span><span class="p">,</span>
        <span class="s1">&#39;order_side&#39;</span><span class="p">:</span> <span class="n">order_side</span><span class="p">,</span>
        <span class="s1">&#39;order_size&#39;</span><span class="p">:</span> <span class="n">order_size</span><span class="p">,</span>
    <span class="p">}</span>


<span class="k">async</span> <span class="k">def</span> <span class="nf">_validate_okx_signal_additional_params</span><span class="p">(</span>
        <span class="n">leverage</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">max_orderbook_limit_price_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">flip_position_if_opposite_side</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
        <span class="n">clear_prior_to_new_order</span><span class="o">=</span><span class="kc">None</span>
<span class="p">):</span>
    <span class="n">leverage</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">leverage</span> <span class="k">else</span> <span class="nb">int</span><span class="p">(</span><span class="n">leverage</span><span class="p">)</span>
    <span class="n">max_orderbook_limit_price_offset</span> <span class="o">=</span> <span class="mi">0</span> \
        <span class="k">if</span> <span class="ow">not</span> <span class="n">max_orderbook_limit_price_offset</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span><span class="n">max_orderbook_limit_price_offset</span><span class="p">)</span>
    <span class="n">flip_position_if_opposite_side</span> <span class="o">=</span> <span class="kc">False</span> \
        <span class="k">if</span> <span class="ow">not</span> <span class="n">flip_position_if_opposite_side</span> <span class="k">else</span> <span class="nb">bool</span><span class="p">(</span><span class="n">flip_position_if_opposite_side</span><span class="p">)</span>
    <span class="n">clear_prior_to_new_order</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">clear_prior_to_new_order</span> <span class="k">else</span> <span class="nb">bool</span><span class="p">(</span><span class="n">clear_prior_to_new_order</span><span class="p">)</span>

    <span class="k">return</span> <span class="p">{</span>
        <span class="s1">&#39;leverage&#39;</span><span class="p">:</span> <span class="n">leverage</span><span class="p">,</span>
        <span class="s1">&#39;max_orderbook_limit_price_offset&#39;</span><span class="p">:</span> <span class="n">max_orderbook_limit_price_offset</span><span class="p">,</span>
        <span class="s1">&#39;flip_position_if_opposite_side&#39;</span><span class="p">:</span> <span class="n">flip_position_if_opposite_side</span><span class="p">,</span>
        <span class="s1">&#39;clear_prior_to_new_order&#39;</span><span class="p">:</span> <span class="n">clear_prior_to_new_order</span><span class="p">,</span>
    <span class="p">}</span>


<div class="viewcode-block" id="prepare_dca">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.prepare_dca">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">prepare_dca</span><span class="p">(</span><span class="n">dca_parameters</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">DCAInputParameters</span><span class="p">],</span> <span class="n">side</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">reference_price</span><span class="p">:</span> <span class="nb">float</span><span class="p">,</span>
                      <span class="n">ccy_contract_size</span><span class="p">:</span> <span class="nb">float</span><span class="p">,</span> <span class="n">ccy_last_price</span><span class="p">:</span> <span class="nb">float</span><span class="p">,</span> <span class="n">usd_to_base_rate</span><span class="p">:</span> <span class="nb">float</span><span class="p">,</span> <span class="n">leverage</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span>
                      <span class="n">min_order_quantity</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">max_market_order_quantity</span><span class="p">:</span> <span class="nb">int</span><span class="p">):</span>
    <span class="c1"># Assert the correct input parameters for dca</span>
    <span class="k">assert</span> <span class="nb">all</span><span class="p">([</span><span class="nb">isinstance</span><span class="p">(</span><span class="n">param</span><span class="p">,</span> <span class="n">DCAInputParameters</span><span class="p">)</span> <span class="k">for</span> <span class="n">param</span> <span class="ow">in</span>
                <span class="n">dca_parameters</span><span class="p">]),</span> <span class="sa">f</span><span class="s1">&#39;The dca_parameters must be a list of DCAInputParameters. </span><span class="si">{</span><span class="n">dca_parameters</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>

    <span class="n">orders</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="k">for</span> <span class="n">params</span> <span class="ow">in</span> <span class="n">dca_parameters</span><span class="p">:</span>
        <span class="n">order_trigger_price</span> <span class="o">=</span> <span class="n">reference_price</span> <span class="o">+</span> <span class="n">params</span><span class="o">.</span><span class="n">trigger_price_offset</span> <span class="k">if</span> <span class="n">side</span> <span class="o">==</span> <span class="s1">&#39;BUY&#39;</span> <span class="k">else</span> <span class="n">reference_price</span> <span class="o">-</span> <span class="n">params</span><span class="o">.</span><span class="n">trigger_price_offset</span>
        <span class="n">order_exec_price</span> <span class="o">=</span> <span class="n">reference_price</span> <span class="o">+</span> <span class="n">params</span><span class="o">.</span><span class="n">execution_price_offset</span> <span class="k">if</span> <span class="n">side</span> <span class="o">==</span> <span class="s1">&#39;BUY&#39;</span> <span class="k">else</span> <span class="n">reference_price</span> <span class="o">-</span> <span class="n">params</span><span class="o">.</span><span class="n">execution_price_offset</span>
        <span class="n">usd_amount</span> <span class="o">=</span> <span class="n">params</span><span class="o">.</span><span class="n">usd_amount</span>

        <span class="n">order_contracts</span> <span class="o">=</span> <span class="n">ccy_usd_to_contracts</span><span class="p">(</span><span class="n">usd_equivalent</span><span class="o">=</span><span class="n">usd_amount</span><span class="p">,</span> <span class="n">ccy_contract_size</span><span class="o">=</span><span class="n">ccy_contract_size</span><span class="p">,</span>
                                               <span class="n">ccy_last_price</span><span class="o">=</span><span class="n">ccy_last_price</span><span class="p">,</span> <span class="n">minimum_contract_size</span><span class="o">=</span><span class="n">min_order_quantity</span><span class="p">,</span>
                                               <span class="n">max_market_contract_size</span><span class="o">=</span><span class="n">max_market_order_quantity</span><span class="p">,</span>
                                               <span class="n">usd_base_ratio</span><span class="o">=</span><span class="n">usd_to_base_rate</span><span class="p">,</span> <span class="n">leverage</span><span class="o">=</span><span class="n">leverage</span><span class="p">)</span>
        <span class="n">orders</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">DCAOrderParameters</span><span class="p">(</span>
            <span class="n">size</span><span class="o">=</span><span class="n">order_contracts</span><span class="p">,</span>
            <span class="n">trigger_price</span><span class="o">=</span><span class="n">order_trigger_price</span><span class="p">,</span>
            <span class="n">execution_price</span><span class="o">=</span><span class="n">order_exec_price</span><span class="p">,</span>
            <span class="nb">type</span><span class="o">=</span><span class="n">params</span><span class="o">.</span><span class="n">order_type</span><span class="p">,</span>
            <span class="n">side</span><span class="o">=</span><span class="n">params</span><span class="o">.</span><span class="n">order_side</span><span class="p">,</span>
            <span class="n">tp_trigger_price_type</span><span class="o">=</span><span class="n">params</span><span class="o">.</span><span class="n">tp_trigger_price_type</span><span class="p">,</span>
            <span class="n">tp_trigger_price_offset</span><span class="o">=</span><span class="n">params</span><span class="o">.</span><span class="n">tp_trigger_price_offset</span><span class="p">,</span>
            <span class="n">tp_execution_price_offset</span><span class="o">=</span><span class="n">params</span><span class="o">.</span><span class="n">tp_execution_price_offset</span><span class="p">,</span>
            <span class="n">sl_trigger_price_type</span><span class="o">=</span><span class="n">params</span><span class="o">.</span><span class="n">sl_trigger_price_type</span><span class="p">,</span>
            <span class="n">sl_trigger_price_offset</span><span class="o">=</span><span class="n">params</span><span class="o">.</span><span class="n">sl_trigger_price_offset</span><span class="p">,</span>
            <span class="n">sl_execution_price_offset</span><span class="o">=</span><span class="n">params</span><span class="o">.</span><span class="n">sl_execution_price_offset</span>
        <span class="p">))</span>

    <span class="k">return</span> <span class="n">orders</span></div>



<div class="viewcode-block" id="validate_okx_signal_params">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.validate_okx_signal_params">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">validate_okx_signal_params</span><span class="p">(</span>
        <span class="n">okx_signal</span><span class="p">:</span> <span class="n">OKXSignalInput</span>
<span class="p">):</span>
    <span class="n">generated_client_order_id</span> <span class="o">=</span> <span class="n">generate_random_string</span><span class="p">(</span><span class="mi">16</span><span class="p">,</span> <span class="s1">&#39;alphanumeric&#39;</span><span class="p">)</span>
    <span class="n">dca_parameters</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="n">validated_order_params</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="n">validated_tp_sl_trail_params</span> <span class="o">=</span> <span class="p">{}</span>

    <span class="k">if</span> <span class="n">okx_signal</span><span class="o">.</span><span class="n">red_button</span><span class="p">:</span>
        <span class="k">return</span> <span class="p">{</span><span class="s1">&#39;red_button&#39;</span><span class="p">:</span> <span class="n">okx_signal</span><span class="o">.</span><span class="n">red_button</span><span class="p">}</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">red_button</span> <span class="o">=</span> <span class="kc">False</span>

    <span class="n">instId_info</span> <span class="o">=</span> <span class="k">await</span> <span class="n">_validate_instID_and_return_ticker_info</span><span class="p">(</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">instID</span><span class="p">)</span>
    <span class="k">assert</span> <span class="n">instId_info</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;Instrument not found. </span><span class="si">{</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">instID</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>

    <span class="n">validated_additional_params</span> <span class="o">=</span> <span class="k">await</span> <span class="n">_validate_okx_signal_additional_params</span><span class="p">(</span>
        <span class="n">leverage</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">leverage</span><span class="p">,</span> <span class="n">max_orderbook_limit_price_offset</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">max_orderbook_limit_price_offset</span><span class="p">,</span>
        <span class="n">flip_position_if_opposite_side</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">flip_position_if_opposite_side</span><span class="p">,</span>
        <span class="n">clear_prior_to_new_order</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">clear_prior_to_new_order</span><span class="p">)</span>
    <span class="n">passed_expiration_test</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="nb">int</span><span class="p">(</span><span class="n">instId_info</span><span class="o">.</span><span class="n">expTime</span><span class="p">)</span> <span class="o">&lt;</span> <span class="nb">int</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">*</span> <span class="mi">1000</span><span class="p">)</span> <span class="k">else</span> <span class="kc">True</span>
    <span class="n">passed_leverage_test</span> <span class="o">=</span> <span class="kc">False</span> <span class="k">if</span> <span class="nb">int</span><span class="p">(</span><span class="n">instId_info</span><span class="o">.</span><span class="n">lever</span><span class="p">)</span> <span class="o">&lt;=</span> <span class="n">validated_additional_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;leverage&#39;</span><span class="p">)</span> <span class="k">else</span> <span class="kc">True</span>
    <span class="k">assert</span> <span class="n">passed_expiration_test</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;Instrument has expired. </span><span class="si">{</span><span class="n">instId_info</span><span class="o">.</span><span class="n">expTime</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="n">passed_leverage_test</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;Instrument has a higher leverage than the one provided. </span><span class="si">{</span><span class="n">instId_info</span><span class="o">.</span><span class="n">lever</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>

    <span class="n">_main_order_flag</span> <span class="o">=</span> <span class="n">okx_signal</span><span class="o">.</span><span class="n">usd_order_size</span> <span class="ow">and</span> <span class="n">okx_signal</span><span class="o">.</span><span class="n">order_side</span>

    <span class="k">if</span> <span class="n">_main_order_flag</span> <span class="ow">or</span> <span class="n">okx_signal</span><span class="o">.</span><span class="n">dca_parameters</span><span class="p">:</span>
        <span class="n">ctValCcy</span> <span class="o">=</span> <span class="n">instId_info</span><span class="o">.</span><span class="n">ctValCcy</span>
        <span class="n">min_order_quantity</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">instId_info</span><span class="o">.</span><span class="n">minSz</span><span class="p">)</span>  <span class="c1"># contracts</span>
        <span class="n">max_market_order_quantity</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">instId_info</span><span class="o">.</span><span class="n">maxMktSz</span><span class="p">)</span>  <span class="c1"># contracts</span>
        <span class="n">ctval_contract_size</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">instId_info</span><span class="o">.</span><span class="n">ctVal</span><span class="p">)</span>
        <span class="n">instId_ticker</span><span class="p">:</span> <span class="n">Ticker</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_ticker</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId_info</span><span class="o">.</span><span class="n">instId</span><span class="p">)</span>
        <span class="k">assert</span> <span class="n">instId_ticker</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;Could not fetch ticker for </span><span class="si">{</span><span class="n">instId_info</span><span class="o">.</span><span class="n">instId</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
        <span class="n">ccy_last_price</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">instId_ticker</span><span class="o">.</span><span class="n">last</span><span class="p">)</span>
        <span class="n">leverage</span> <span class="o">=</span> <span class="n">validated_additional_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;leverage&#39;</span><span class="p">)</span> <span class="ow">or</span> <span class="k">await</span> <span class="n">get_leverage</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instId_info</span><span class="o">.</span><span class="n">instId</span><span class="p">,</span>
                                                                                     <span class="n">mgnMode</span><span class="o">=</span><span class="s1">&#39;isolated&#39;</span><span class="p">)</span>

        <span class="n">usd_to_base_rate</span> <span class="o">=</span> <span class="mi">1</span>  <span class="c1"># TODO use the USD to USDT and USDC ratio but 1 is close enough</span>

        <span class="k">if</span> <span class="n">okx_signal</span><span class="o">.</span><span class="n">dca_parameters</span><span class="p">:</span>
            <span class="n">dca_parameters</span><span class="p">:</span> <span class="p">[</span><span class="n">DCAOrderParameters</span><span class="p">]</span> <span class="o">=</span> <span class="k">await</span> <span class="n">prepare_dca</span><span class="p">(</span>
                <span class="n">dca_parameters</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">dca_parameters</span><span class="p">,</span>
                <span class="n">side</span><span class="o">=</span><span class="n">validated_order_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;order_side&#39;</span><span class="p">),</span>
                <span class="n">reference_price</span><span class="o">=</span><span class="n">ccy_last_price</span><span class="p">,</span>
                <span class="n">ccy_contract_size</span><span class="o">=</span><span class="n">ctval_contract_size</span><span class="p">,</span> <span class="n">ccy_last_price</span><span class="o">=</span><span class="n">ccy_last_price</span><span class="p">,</span>
                <span class="n">usd_to_base_rate</span><span class="o">=</span><span class="n">usd_to_base_rate</span><span class="p">,</span> <span class="n">leverage</span><span class="o">=</span><span class="n">leverage</span><span class="p">,</span>
                <span class="n">min_order_quantity</span><span class="o">=</span><span class="n">min_order_quantity</span><span class="p">,</span>
                <span class="n">max_market_order_quantity</span><span class="o">=</span><span class="n">max_market_order_quantity</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">_main_order_flag</span><span class="p">:</span>

        <span class="n">usd_amount</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">usd_order_size</span><span class="p">)</span>
        <span class="n">order_contracts</span> <span class="o">=</span> <span class="n">ccy_usd_to_contracts</span><span class="p">(</span><span class="n">usd_equivalent</span><span class="o">=</span><span class="n">usd_amount</span><span class="p">,</span> <span class="n">ccy_contract_size</span><span class="o">=</span><span class="n">ctval_contract_size</span><span class="p">,</span>
                                               <span class="n">ccy_last_price</span><span class="o">=</span><span class="n">ccy_last_price</span><span class="p">,</span> <span class="n">minimum_contract_size</span><span class="o">=</span><span class="n">min_order_quantity</span><span class="p">,</span>
                                               <span class="n">max_market_contract_size</span><span class="o">=</span><span class="n">max_market_order_quantity</span><span class="p">,</span>
                                               <span class="n">usd_base_ratio</span><span class="o">=</span><span class="n">usd_to_base_rate</span><span class="p">,</span> <span class="n">leverage</span><span class="o">=</span><span class="n">leverage</span><span class="p">,</span>
                                               <span class="n">ctValCcy</span><span class="o">=</span><span class="n">ctValCcy</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Number of contracts you can buy: </span><span class="si">{</span><span class="n">order_contracts</span><span class="si">}</span><span class="s2"> </span><span class="si">{</span><span class="n">instId_info</span><span class="o">.</span><span class="n">instId</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>

        <span class="c1"># Convert these into trailing_stop_callback_offset to trailing_stop_callback_ratio</span>
        <span class="k">if</span> <span class="n">okx_signal</span><span class="o">.</span><span class="n">trailing_stop_callback_offset</span><span class="p">:</span>
            <span class="n">trailing_stop_callback_offset</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">trailing_stop_callback_offset</span><span class="p">)</span>
            <span class="n">trailing_stop_callback_ratio</span> <span class="o">=</span> <span class="n">trailing_stop_callback_offset</span> <span class="o">/</span> <span class="n">ccy_last_price</span>
            <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">trailing_stop_callback_ratio</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="c1"># Min is 0,001 and max is 1</span>
            <span class="k">if</span> <span class="n">trailing_stop_callback_ratio</span> <span class="o">&lt;</span> <span class="mf">0.001</span><span class="p">:</span>
                <span class="n">trailing_stop_callback_ratio</span> <span class="o">=</span> <span class="mf">0.001</span>
            <span class="k">if</span> <span class="n">trailing_stop_callback_ratio</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
                <span class="n">trailing_stop_callback_ratio</span> <span class="o">=</span> <span class="mi">1</span>

            <span class="n">trailing_stop_callback_offset</span> <span class="o">=</span> <span class="nb">round</span><span class="p">(</span><span class="n">trailing_stop_callback_ratio</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">trailing_stop_callback_offset</span> <span class="o">=</span> <span class="mf">0.0</span>

        <span class="n">validated_order_params</span> <span class="o">=</span> <span class="k">await</span> <span class="n">_validate_okx_signal_order_params</span><span class="p">(</span>
            <span class="n">order_type</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">order_type</span><span class="p">,</span> <span class="n">order_side</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">order_side</span><span class="p">,</span>
            <span class="n">order_size</span><span class="o">=</span><span class="n">order_contracts</span><span class="p">)</span>

        <span class="n">validated_tp_sl_trail_params</span> <span class="o">=</span> <span class="k">await</span> <span class="n">_validate_okx_signal_input_tp_sl_trail_params</span><span class="p">(</span>
            <span class="n">sl_trigger_price_offset</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">sl_trigger_price_offset</span><span class="p">,</span>
            <span class="n">tp_trigger_price_offset</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">tp_trigger_price_offset</span><span class="p">,</span>
            <span class="n">sl_execution_price_offset</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">sl_execution_price_offset</span><span class="p">,</span>
            <span class="n">tp_execution_price_offset</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">tp_execution_price_offset</span><span class="p">,</span>
            <span class="n">trailing_stop_activation_price_offset</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">trailing_stop_activation_price_offset</span><span class="p">,</span>
            <span class="n">trailing_stop_callback_offset</span><span class="o">=</span><span class="n">trailing_stop_callback_offset</span><span class="p">,</span>
            <span class="n">max_orderbook_limit_price_offset</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">max_orderbook_limit_price_offset</span><span class="p">,</span>
            <span class="n">flip_position_if_opposite_side</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">flip_position_if_opposite_side</span><span class="p">,</span>
            <span class="n">tp_trigger_price_type</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">tp_trigger_price_type</span><span class="p">,</span>
            <span class="n">sl_trigger_price_type</span><span class="o">=</span><span class="n">okx_signal</span><span class="o">.</span><span class="n">sl_trigger_price_type</span><span class="p">)</span>

    <span class="n">result</span> <span class="o">=</span> <span class="p">{</span>
        <span class="s1">&#39;instID&#39;</span><span class="p">:</span> <span class="n">instId_info</span><span class="o">.</span><span class="n">instId</span><span class="p">,</span>
        <span class="s1">&#39;order_size&#39;</span><span class="p">:</span> <span class="n">validated_order_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;order_size&#39;</span><span class="p">),</span>
        <span class="s1">&#39;leverage&#39;</span><span class="p">:</span> <span class="n">validated_additional_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;leverage&#39;</span><span class="p">),</span>
        <span class="s1">&#39;order_side&#39;</span><span class="p">:</span> <span class="n">validated_order_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;order_side&#39;</span><span class="p">),</span>
        <span class="s1">&#39;order_type&#39;</span><span class="p">:</span> <span class="n">validated_order_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;order_type&#39;</span><span class="p">),</span>
        <span class="s1">&#39;max_orderbook_limit_price_offset&#39;</span><span class="p">:</span> <span class="n">validated_additional_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;max_orderbook_limit_price_offset&#39;</span><span class="p">),</span>
        <span class="s1">&#39;flip_position_if_opposite_side&#39;</span><span class="p">:</span> <span class="n">validated_additional_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;flip_position_if_opposite_side&#39;</span><span class="p">),</span>
        <span class="s1">&#39;clear_prior_to_new_order&#39;</span><span class="p">:</span> <span class="n">validated_additional_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;clear_prior_to_new_order&#39;</span><span class="p">),</span>
        <span class="s1">&#39;red_button&#39;</span><span class="p">:</span> <span class="n">red_button</span><span class="p">,</span>
        <span class="s1">&#39;sl_trigger_price_offset&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;sl_trigger_price_offset&#39;</span><span class="p">),</span>
        <span class="s1">&#39;tp_trigger_price_offset&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;tp_trigger_price_offset&#39;</span><span class="p">),</span>
        <span class="s1">&#39;tp_trigger_price_type&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;tp_trigger_price_type&#39;</span><span class="p">),</span>
        <span class="s1">&#39;sl_execution_price_offset&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;sl_execution_price_offset&#39;</span><span class="p">),</span>
        <span class="s1">&#39;tp_execution_price_offset&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;tp_execution_price_offset&#39;</span><span class="p">),</span>
        <span class="s1">&#39;sl_trigger_price_type&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;sl_trigger_price_type&#39;</span><span class="p">),</span>
        <span class="s1">&#39;trailing_stop_activation_price_offset&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span>
            <span class="s1">&#39;trailing_stop_activation_price_offset&#39;</span><span class="p">),</span>
        <span class="s1">&#39;trailing_stop_callback_offset&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;trailing_stop_callback_offset&#39;</span><span class="p">),</span>
        <span class="c1">#</span>
        <span class="s1">&#39;generated_client_order_id&#39;</span><span class="p">:</span> <span class="n">generated_client_order_id</span><span class="p">,</span>
        <span class="s1">&#39;take_profit_activated&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;take_profit_activated&#39;</span><span class="p">),</span>
        <span class="s1">&#39;stop_loss_activated&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;stop_loss_activated&#39;</span><span class="p">),</span>
        <span class="s1">&#39;trailing_stop_loss_activated&#39;</span><span class="p">:</span> <span class="n">validated_tp_sl_trail_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;trailing_stop_loss_activated&#39;</span><span class="p">),</span>
        <span class="s1">&#39;dca_parameters&#39;</span><span class="p">:</span> <span class="n">dca_parameters</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">result</span></div>



<div class="viewcode-block" id="okx_signal_handler">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.okx_signal_handler">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">okx_signal_handler</span><span class="p">(</span>
        <span class="n">instID</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="n">usd_order_size</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">leverage</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">order_side</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">order_type</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">max_orderbook_limit_price_offset</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">flip_position_if_opposite_side</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span>
        <span class="n">clear_prior_to_new_order</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span>
        <span class="n">red_button</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span>
        <span class="n">sl_trigger_price_offset</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">tp_trigger_price_offset</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">tp_trigger_price_type</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">sl_execution_price_offset</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">tp_execution_price_offset</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">sl_trigger_price_type</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">trailing_stop_activation_price_offset</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">trailing_stop_callback_offset</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">dca_parameters</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">DCAInputParameters</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span>
<span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Handles trading signals for the OKX platform, executing trades based on the specified parameters and current</span>
<span class="sd">    market conditions.</span>

<span class="sd">    Overview: 1. Validates and processes input parameters, preparing the trading signal. 2. Checks and manages</span>
<span class="sd">    current positions based on new signal, potentially flipping positions or clearing orders as configured. 3.</span>
<span class="sd">    Calculates and sets order parameters such as price and size, leveraging current market data and user preferences.</span>
<span class="sd">    4. Executes the trading actions (placing/canceling orders, opening/closing positions) on the OKX platform. 5.</span>
<span class="sd">    Fetches and returns an updated status report of the instrument, reflecting the changes made by the executed signal.</span>

<span class="sd">    Process Flow: The `okx_signal_handler` function is a complex asynchronous function designed to handle trading</span>
<span class="sd">    signals for the OKX platform, covering a wide range of trading strategies and actions. Here is a step-by-step</span>
<span class="sd">    structural and behavioral walkthrough of the main activities within the function, highlighting how it interacts</span>
<span class="sd">    with other helper functions:</span>

<span class="sd">        1. **Initialize OKX Signal Input**: It creates an instance of `OKXSignalInput` with all the provided</span>
<span class="sd">        parameters. This step is crucial for collecting all user inputs regarding the trading signal they wish to</span>
<span class="sd">        execute.</span>

<span class="sd">        2. **Pre-validation and Setup**: - Validates trading mode (`TD_MODE`) and position type (`POSSIDETYPE`) to</span>
<span class="sd">        ensure they are within acceptable parameters. - If the `red_button` parameter is true, the function triggers</span>
<span class="sd">        emergency actions to close all positions, cancel all orders, and return the status of these actions.</span>

<span class="sd">        3. **Validate Parameters**: Calls `validate_okx_signal_params` to validate and process input parameters</span>
<span class="sd">        comprehensively. This includes instrument ID validation, leverage checks, and configuration of additional</span>
<span class="sd">        parameters like order size, type, and various trading strategies (e.g., stop loss, take profit).</span>

<span class="sd">        4. **Initial Data Fetching**: Retrieves necessary initial data related to the trading account and the</span>
<span class="sd">        specific instrument being traded. This might include balance details, account configurations, and the current</span>
<span class="sd">        status report of the instrument.</span>

<span class="sd">        5. **Set Leverage**: If leverage is specified, it sets the leverage for the trading account according to the</span>
<span class="sd">        provided value.</span>

<span class="sd">        6. **Order and Position Management**: - Checks for existing positions and manages them based on the new</span>
<span class="sd">        signal. This includes closing positions, canceling orders, or flipping positions if configured to do so by</span>
<span class="sd">        the user. - If there are no conflicting positions or if the user has opted to clear previous orders and</span>
<span class="sd">        positions, it proceeds to calculate and set new order parameters.</span>

<span class="sd">        7. **Order Execution**: - Retrieves current market data (e.g., ticker information) to determine reference</span>
<span class="sd">        prices for order placement. - Calls `prepare_limit_price` to calculate the appropriate limit price for the</span>
<span class="sd">        order based on current market conditions and user specifications. - Constructs and sends order requests,</span>
<span class="sd">        including handling of special order types like take profit, stop loss, and trailing stop losses.</span>

<span class="sd">        8. **Dollar-Cost Averaging (DCA) Orders**: - If DCA parameters are provided, it prepares and sends multiple</span>
<span class="sd">        DCA orders based on the specified strategies and market conditions. - Each DCA order is configured with</span>
<span class="sd">        trigger prices, execution prices, and optional stop loss/take profit parameters.</span>

<span class="sd">        9. **Final Actions**: - After all trading actions have been attempted, it fetches and returns an updated</span>
<span class="sd">        status report for the instrument, reflecting the changes made by the executed signal. - Handles exceptions</span>
<span class="sd">        and errors throughout the process, ensuring that any issues are caught and logged, with appropriate cleanup</span>
<span class="sd">        actions taken if necessary.</span>

<span class="sd">        This function encapsulates a comprehensive set of trading strategies and operations, leveraging asynchronous</span>
<span class="sd">        programming to handle market data fetching, order preparation, and execution in a non-blocking manner. It</span>
<span class="sd">        demonstrates a complex integration of trading logic, error handling, and user input validation to manage</span>
<span class="sd">        trading signals on the OKX platform effectively.</span>

<span class="sd">        :raises Exception: Catches and logs any exceptions that occur during signal handling, providing detailed</span>
<span class="sd">        error information.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">okx_signal_input</span><span class="p">:</span> <span class="n">OKXSignalInput</span> <span class="o">=</span> <span class="n">OKXSignalInput</span><span class="p">(</span>
        <span class="n">instID</span><span class="o">=</span><span class="n">instID</span><span class="p">,</span>
        <span class="n">usd_order_size</span><span class="o">=</span><span class="n">usd_order_size</span><span class="p">,</span>
        <span class="n">leverage</span><span class="o">=</span><span class="n">leverage</span><span class="p">,</span>
        <span class="n">order_side</span><span class="o">=</span><span class="n">order_side</span><span class="p">,</span>
        <span class="n">order_type</span><span class="o">=</span><span class="n">order_type</span><span class="p">,</span>
        <span class="n">max_orderbook_limit_price_offset</span><span class="o">=</span><span class="n">max_orderbook_limit_price_offset</span><span class="p">,</span>
        <span class="n">flip_position_if_opposite_side</span><span class="o">=</span><span class="n">flip_position_if_opposite_side</span><span class="p">,</span>
        <span class="n">clear_prior_to_new_order</span><span class="o">=</span><span class="n">clear_prior_to_new_order</span><span class="p">,</span>
        <span class="n">red_button</span><span class="o">=</span><span class="n">red_button</span><span class="p">,</span>
        <span class="n">sl_trigger_price_offset</span><span class="o">=</span><span class="n">sl_trigger_price_offset</span><span class="p">,</span>
        <span class="n">tp_trigger_price_offset</span><span class="o">=</span><span class="n">tp_trigger_price_offset</span><span class="p">,</span>
        <span class="n">tp_trigger_price_type</span><span class="o">=</span><span class="n">tp_trigger_price_type</span><span class="p">,</span>
        <span class="n">sl_execution_price_offset</span><span class="o">=</span><span class="n">sl_execution_price_offset</span><span class="p">,</span>
        <span class="n">tp_execution_price_offset</span><span class="o">=</span><span class="n">tp_execution_price_offset</span><span class="p">,</span>
        <span class="n">sl_trigger_price_type</span><span class="o">=</span><span class="n">sl_trigger_price_type</span><span class="p">,</span>
        <span class="n">trailing_stop_activation_price_offset</span><span class="o">=</span><span class="n">trailing_stop_activation_price_offset</span><span class="p">,</span>
        <span class="n">trailing_stop_callback_offset</span><span class="o">=</span><span class="n">trailing_stop_callback_offset</span><span class="p">,</span>
        <span class="n">dca_parameters</span><span class="o">=</span><span class="n">dca_parameters</span>
    <span class="p">)</span>
    <span class="n">TD_MODE</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;isolated&#39;</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>  <span class="c1"># here for completeness, but assumed to be isolated</span>
    <span class="n">POSSIDETYPE</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;net&#39;</span>  <span class="c1"># net or long/short, need to cancel all orders/positions to change</span>
    <span class="k">assert</span> <span class="n">TD_MODE</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;isolated&#39;</span><span class="p">,</span> <span class="s1">&#39;crossed&#39;</span><span class="p">],</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">TD_MODE</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">assert</span> <span class="n">POSSIDETYPE</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;net&#39;</span><span class="p">,</span> <span class="s1">&#39;long&#39;</span><span class="p">,</span> <span class="s1">&#39;short&#39;</span><span class="p">],</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">POSSIDETYPE</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>

    <span class="k">if</span> <span class="n">red_button</span><span class="p">:</span>
        <span class="n">all_closed_positions</span> <span class="o">=</span> <span class="k">await</span> <span class="n">close_all_positions</span><span class="p">()</span>
        <span class="n">all_cancelled_orders</span> <span class="o">=</span> <span class="k">await</span> <span class="n">cancel_all_orders</span><span class="p">()</span>
        <span class="n">all_cancelled_algo_orders</span> <span class="o">=</span> <span class="k">await</span> <span class="n">cancel_all_algo_orders_with_params</span><span class="p">()</span>
        <span class="n">all_positions</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_all_positions</span><span class="p">()</span>
        <span class="n">all_orders</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_all_orders</span><span class="p">()</span>
        <span class="n">all_algo_orders</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_all_algo_orders</span><span class="p">()</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">all_closed_positions</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">all_cancelled_orders</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">all_cancelled_algo_orders</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">all_positions</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">all_orders</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">all_algo_orders</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="k">return</span> <span class="p">{</span><span class="s1">&#39;red_button&#39;</span><span class="p">:</span> <span class="s1">&#39;ok&#39;</span><span class="p">,</span>
                <span class="s1">&#39;all_closed_positions&#39;</span><span class="p">:</span> <span class="n">all_closed_positions</span><span class="p">,</span>
                <span class="s1">&#39;all_cancelled_orders&#39;</span><span class="p">:</span> <span class="n">all_cancelled_orders</span><span class="p">,</span>
                <span class="s1">&#39;all_cancelled_algo_orders&#39;</span><span class="p">:</span> <span class="n">all_cancelled_algo_orders</span><span class="p">,</span>
                <span class="s1">&#39;all_positions&#39;</span><span class="p">:</span> <span class="n">all_positions</span><span class="p">,</span>
                <span class="s1">&#39;all_orders&#39;</span><span class="p">:</span> <span class="n">all_orders</span><span class="p">,</span>
                <span class="s1">&#39;all_algo_orders&#39;</span><span class="p">:</span> <span class="n">all_algo_orders</span>
                <span class="p">}</span>

    <span class="c1"># Clean Input Data</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">validated_params</span> <span class="o">=</span> <span class="k">await</span> <span class="n">validate_okx_signal_params</span><span class="p">(</span><span class="n">okx_signal_input</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="k">return</span> <span class="p">{</span><span class="s1">&#39;error&#39;</span><span class="p">:</span> <span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="p">)}</span>

    <span class="c1"># Get back all the values validated</span>
    <span class="n">instID</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;instID&#39;</span><span class="p">)</span>
    <span class="n">order_size</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;order_size&#39;</span><span class="p">)</span>
    <span class="n">leverage</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;leverage&#39;</span><span class="p">)</span>
    <span class="n">order_side</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;order_side&#39;</span><span class="p">)</span>
    <span class="n">order_type</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;order_type&#39;</span><span class="p">)</span>
    <span class="n">max_orderbook_limit_price_offset</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;max_orderbook_limit_price_offset&#39;</span><span class="p">)</span>
    <span class="n">flip_position_if_opposite_side</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;flip_position_if_opposite_side&#39;</span><span class="p">)</span>
    <span class="n">clear_prior_to_new_order</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;clear_prior_to_new_order&#39;</span><span class="p">)</span>
    <span class="n">red_button</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;red_button&#39;</span><span class="p">)</span>
    <span class="n">sl_trigger_price_offset</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;sl_trigger_price_offset&#39;</span><span class="p">)</span>
    <span class="n">tp_trigger_price_offset</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;tp_trigger_price_offset&#39;</span><span class="p">)</span>
    <span class="n">tp_trigger_price_type</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;tp_trigger_price_type&#39;</span><span class="p">)</span>
    <span class="n">sl_execution_price_offset</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;sl_execution_price_offset&#39;</span><span class="p">)</span>
    <span class="n">tp_execution_price_offset</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;tp_execution_price_offset&#39;</span><span class="p">)</span>
    <span class="n">sl_trigger_price_type</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;sl_trigger_price_type&#39;</span><span class="p">)</span>
    <span class="n">trailing_stop_activation_price_offset</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;trailing_stop_activation_price_offset&#39;</span><span class="p">)</span>
    <span class="n">trailing_stop_callback_offset</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;trailing_stop_callback_offset&#39;</span><span class="p">)</span>
    <span class="n">generated_client_order_id</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;generated_client_order_id&#39;</span><span class="p">)</span>
    <span class="n">take_profit_activated</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;take_profit_activated&#39;</span><span class="p">)</span>
    <span class="n">stop_loss_activated</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;stop_loss_activated&#39;</span><span class="p">)</span>
    <span class="n">trailing_stop_loss_activated</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;trailing_stop_loss_activated&#39;</span><span class="p">)</span>
    <span class="n">dca_parameters</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">DCAOrderParameters</span><span class="p">]</span> <span class="ow">or</span> <span class="kc">None</span> <span class="o">=</span> <span class="n">validated_params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;dca_parameters&#39;</span><span class="p">)</span>

    <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">instID</span><span class="p">,</span> <span class="nb">str</span><span class="p">),</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">instID</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">if</span> <span class="n">clear_prior_to_new_order</span><span class="p">:</span>
        <span class="k">await</span> <span class="n">clear_orders_and_positions_for_instrument</span><span class="p">(</span><span class="n">instID</span><span class="p">)</span>

    <span class="p">(</span><span class="n">simplified_balance_details</span><span class="p">,</span> <span class="n">account_config</span><span class="p">,</span> <span class="n">instrument_status_report</span><span class="p">)</span> <span class="o">=</span> <span class="k">await</span> <span class="n">fetch_initial_data</span><span class="p">(</span><span class="n">TD_MODE</span><span class="p">,</span>
                                                                                                      <span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">leverage</span> <span class="ow">and</span> <span class="n">leverage</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">accountAPI</span><span class="o">.</span><span class="n">set_leverage</span><span class="p">(</span>
            <span class="n">lever</span><span class="o">=</span><span class="n">leverage</span><span class="p">,</span>
            <span class="n">mgnMode</span><span class="o">=</span><span class="n">TD_MODE</span><span class="p">,</span>
            <span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">,</span>
            <span class="n">posSide</span><span class="o">=</span><span class="n">POSSIDETYPE</span>
        <span class="p">)</span>

    <span class="n">position</span> <span class="o">=</span> <span class="n">instrument_status_report</span><span class="o">.</span><span class="n">positions</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">if</span> <span class="nb">len</span><span class="p">(</span>
        <span class="n">instrument_status_report</span><span class="o">.</span><span class="n">positions</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="k">else</span> <span class="kc">None</span>  <span class="c1"># we are only using net so only one position</span>

    <span class="k">if</span> <span class="n">order_side</span> <span class="ow">and</span> <span class="n">order_size</span><span class="p">:</span>
        <span class="n">ticker</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_ticker</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">ticker</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="n">ask_price</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">ticker</span><span class="o">.</span><span class="n">askPx</span><span class="p">)</span> <span class="k">if</span> <span class="n">ticker</span><span class="o">.</span><span class="n">askPx</span> <span class="k">else</span> <span class="n">ticker</span><span class="o">.</span><span class="n">bidPx</span>  <span class="c1"># fixme sometimes okx returns &#39;&#39; for askPx</span>
        <span class="n">bid_price</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">ticker</span><span class="o">.</span><span class="n">bidPx</span><span class="p">)</span>
        <span class="n">reference_price</span> <span class="o">=</span> <span class="n">ask_price</span> <span class="k">if</span> <span class="n">order_side</span> <span class="o">==</span> <span class="s1">&#39;buy&#39;</span> <span class="k">else</span> <span class="n">bid_price</span>
        <span class="k">if</span> <span class="n">position</span><span class="p">:</span>
            <span class="n">position_side</span> <span class="o">=</span> <span class="s1">&#39;buy&#39;</span> <span class="k">if</span> <span class="nb">float</span><span class="p">(</span><span class="n">position</span><span class="o">.</span><span class="n">pos</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="k">else</span> <span class="s1">&#39;sell&#39;</span> <span class="k">if</span> <span class="nb">float</span><span class="p">(</span>
                <span class="n">position</span><span class="o">.</span><span class="n">pos</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span> <span class="k">else</span> <span class="kc">None</span>  <span class="c1"># we are only using net so only one position</span>
            <span class="k">if</span> <span class="n">position_side</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
                <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Closing all positions for </span><span class="si">{</span><span class="n">instID</span><span class="w"> </span><span class="si">= }</span><span class="s1"> due to 0 net position&#39;</span><span class="p">)</span>
                <span class="k">await</span> <span class="n">close_all_positions</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
                <span class="k">await</span> <span class="n">cancel_all_algo_orders_with_params</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
                <span class="k">await</span> <span class="n">cancel_all_orders</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
            <span class="k">elif</span> <span class="n">order_side</span> <span class="ow">and</span> <span class="n">position_side</span> <span class="o">!=</span> <span class="n">order_side</span><span class="p">:</span>
                <span class="k">if</span> <span class="n">flip_position_if_opposite_side</span><span class="p">:</span>
                    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Flipping position from </span><span class="si">{</span><span class="n">position_side</span><span class="w"> </span><span class="si">= }</span><span class="s1"> to </span><span class="si">{</span><span class="n">order_side</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
                    <span class="k">await</span> <span class="n">close_all_positions</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
                    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Closed all positions for </span><span class="si">{</span><span class="n">instID</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>

                    <span class="n">cancelled_orders</span> <span class="o">=</span> <span class="k">await</span> <span class="n">cancel_all_orders</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
                    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Cancelling orders to flip position: </span><span class="se">\n</span><span class="s2">&quot;</span>
                          <span class="sa">f</span><span class="s2">&quot;    </span><span class="si">{</span><span class="n">cancelled_orders</span><span class="w"> </span><span class="si">= }</span><span class="s2">&quot;</span><span class="p">)</span>
                    <span class="n">cancelled_algo_orders</span> <span class="o">=</span> <span class="k">await</span> <span class="n">cancel_all_algo_orders_with_params</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
                    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Cancelling Algo orders to flip position: </span><span class="se">\n</span><span class="s2">&quot;</span>
                          <span class="sa">f</span><span class="s2">&quot;    </span><span class="si">{</span><span class="n">cancelled_algo_orders</span><span class="w"> </span><span class="si">= }</span><span class="s2">&quot;</span><span class="p">)</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Closing all positions for </span><span class="si">{</span><span class="n">instID</span><span class="w"> </span><span class="si">= }</span><span class="s1"> due to </span><span class="si">{</span><span class="n">position_side</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
                    <span class="n">agg_pos</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">position</span><span class="o">.</span><span class="n">pos</span><span class="p">)</span> <span class="o">+</span> <span class="n">order_size</span>
                    <span class="k">if</span> <span class="n">agg_pos</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
                        <span class="n">dominant_pos_side</span> <span class="o">=</span> <span class="s1">&#39;buy&#39;</span>
                    <span class="k">elif</span> <span class="n">agg_pos</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
                        <span class="n">dominant_pos_side</span> <span class="o">=</span> <span class="s1">&#39;sell&#39;</span>
                    <span class="k">else</span><span class="p">:</span>
                        <span class="n">dominant_pos_side</span> <span class="o">=</span> <span class="kc">None</span>

                    <span class="k">if</span> <span class="n">dominant_pos_side</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
                        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">dominant_pos_side</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
                        <span class="k">if</span> <span class="n">dominant_pos_side</span> <span class="o">!=</span> <span class="n">order_side</span><span class="p">:</span>
                            <span class="c1"># This means that the future to be position net direction is not the same as the order side</span>
                            <span class="c1"># thus we need to cancel all orders that are not on the dominant side</span>
                            <span class="c1"># and prevent new algo orders from being placed</span>
                            <span class="n">take_profit_activated</span> <span class="o">=</span> <span class="kc">False</span>
                            <span class="n">stop_loss_activated</span> <span class="o">=</span> <span class="kc">False</span>
                            <span class="n">trailing_stop_loss_activated</span> <span class="o">=</span> <span class="kc">False</span>
                        <span class="k">else</span><span class="p">:</span>
                            <span class="n">orders_to_cancel</span> <span class="o">=</span> <span class="p">[]</span>
                            <span class="k">for</span> <span class="n">order</span> <span class="ow">in</span> <span class="n">instrument_status_report</span><span class="o">.</span><span class="n">orders</span><span class="p">:</span>
                                <span class="k">if</span> <span class="n">order</span><span class="o">.</span><span class="n">side</span> <span class="o">!=</span> <span class="n">dominant_pos_side</span><span class="p">:</span>
                                    <span class="n">orders_to_cancel</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">order</span><span class="p">)</span>
                            <span class="n">algo_orders_to_cancel</span> <span class="o">=</span> <span class="p">[]</span>
                            <span class="k">for</span> <span class="n">algo_order</span> <span class="ow">in</span> <span class="n">instrument_status_report</span><span class="o">.</span><span class="n">algo_orders</span><span class="p">:</span>
                                <span class="k">if</span> <span class="n">algo_order</span><span class="o">.</span><span class="n">side</span> <span class="o">!=</span> <span class="n">dominant_pos_side</span><span class="p">:</span>
                                    <span class="n">algo_orders_to_cancel</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">algo_order</span><span class="p">)</span>

                            <span class="k">if</span> <span class="n">orders_to_cancel</span><span class="p">:</span>
                                <span class="k">await</span> <span class="n">cancel_all_orders</span><span class="p">(</span><span class="n">orders_list</span><span class="o">=</span><span class="n">orders_to_cancel</span><span class="p">)</span>
                                <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Cancelling orders to prep for incoming orders: </span><span class="se">\n</span><span class="s2">&quot;</span>
                                      <span class="sa">f</span><span class="s2">&quot;    </span><span class="si">{</span><span class="n">orders_to_cancel</span><span class="w"> </span><span class="si">= }</span><span class="s2">&quot;</span><span class="p">)</span>
                            <span class="k">if</span> <span class="n">algo_orders_to_cancel</span><span class="p">:</span>
                                <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">algo_orders_to_cancel</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
                                <span class="n">cancelled_algo_orders</span> <span class="o">=</span> <span class="n">cancel_all_algo_orders_with_params</span><span class="p">(</span>
                                    <span class="n">algo_orders_list</span><span class="o">=</span><span class="n">algo_orders_to_cancel</span><span class="p">)</span>
                                <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Cancelling Algo orders to prep for incoming orders: </span><span class="se">\n</span><span class="s2">&quot;</span>
                                      <span class="sa">f</span><span class="s2">&quot;    </span><span class="si">{</span><span class="n">cancelled_algo_orders</span><span class="w"> </span><span class="si">= }</span><span class="s2">&quot;</span><span class="p">)</span>

                    <span class="k">else</span><span class="p">:</span>
                        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;The new position will result in a net 0 after the incoming orders&#39;</span>
                              <span class="sa">f</span><span class="s1">&#39; </span><span class="si">{</span><span class="n">position_side</span><span class="w"> </span><span class="si">= }</span><span class="s1"> and the order side is </span><span class="si">{</span><span class="n">order_side</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
                              <span class="sa">f</span><span class="s1">&#39; with </span><span class="si">{</span><span class="n">position</span><span class="o">.</span><span class="n">pos</span><span class="w"> </span><span class="si">= }</span><span class="s1"> and </span><span class="si">{</span><span class="n">order_size</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
                        <span class="k">await</span> <span class="n">cancel_all_orders</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
                        <span class="k">await</span> <span class="n">cancel_all_algo_orders_with_params</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>

        <span class="n">order_request_dict</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span>
            <span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">,</span>
            <span class="n">tdMode</span><span class="o">=</span><span class="n">TD_MODE</span><span class="p">,</span>
            <span class="n">side</span><span class="o">=</span><span class="n">order_side</span><span class="p">,</span>
            <span class="n">posSide</span><span class="o">=</span><span class="n">POSSIDETYPE</span><span class="p">,</span>
            <span class="n">ordType</span><span class="o">=</span><span class="n">order_type</span><span class="p">,</span>  <span class="c1"># post_only, limit, market</span>
            <span class="n">sz</span><span class="o">=</span><span class="n">order_size</span><span class="p">,</span>
            <span class="n">clOrdId</span><span class="o">=</span><span class="n">generated_client_order_id</span><span class="p">,</span>
        <span class="p">)</span>

        <span class="k">if</span> <span class="n">order_type</span> <span class="o">!=</span> <span class="s1">&#39;market&#39;</span><span class="p">:</span>
            <span class="n">order_book</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_order_book</span><span class="p">(</span><span class="n">instID</span><span class="p">,</span> <span class="mi">400</span><span class="p">)</span>
            <span class="n">limit_price</span> <span class="o">=</span> <span class="k">await</span> <span class="n">prepare_limit_price</span><span class="p">(</span><span class="n">order_book</span><span class="p">,</span> <span class="n">order_size</span><span class="p">,</span> <span class="n">order_side</span><span class="p">,</span> <span class="n">reference_price</span><span class="p">,</span>
                                                    <span class="n">max_orderbook_price_offset</span><span class="o">=</span><span class="n">max_orderbook_limit_price_offset</span><span class="p">)</span>
            <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Setting New Target Limit Price to </span><span class="si">{</span><span class="n">limit_price</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>

            <span class="n">order_request_dict</span><span class="p">[</span><span class="s1">&#39;px&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">limit_price</span>

        <span class="c1"># Todo TP/SL add options for ordertypes other than limit, similar to how TP/SL&#39;s for DCA are configured</span>
        <span class="k">if</span> <span class="n">take_profit_activated</span><span class="p">:</span>
            <span class="n">stop_surplus_trigger_price</span><span class="p">,</span> <span class="n">stop_surplus_execute_price</span> <span class="o">=</span> <span class="n">calculate_tp_stop_prices_usd</span><span class="p">(</span>
                <span class="n">order_side</span><span class="o">=</span><span class="n">order_side</span><span class="p">,</span>
                <span class="n">reference_price</span><span class="o">=</span><span class="n">reference_price</span><span class="p">,</span>
                <span class="n">tp_trigger_usd</span><span class="o">=</span><span class="n">tp_trigger_price_offset</span><span class="p">,</span>
                <span class="n">tp_execute_usd</span><span class="o">=</span><span class="n">tp_execution_price_offset</span><span class="p">,</span>
            <span class="p">)</span>
            <span class="n">order_request_dict</span><span class="o">.</span><span class="n">update</span><span class="p">(</span>
                <span class="n">tpTriggerPx</span><span class="o">=</span><span class="n">stop_surplus_trigger_price</span><span class="p">,</span>
                <span class="n">tpOrdPx</span><span class="o">=</span><span class="n">stop_surplus_execute_price</span><span class="p">,</span>
                <span class="n">tpTriggerPxType</span><span class="o">=</span><span class="n">tp_trigger_price_type</span><span class="p">,</span>
                <span class="n">algoClOrdId</span><span class="o">=</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">generated_client_order_id</span><span class="si">}</span><span class="s1">TPORSL&#39;</span>
            <span class="p">)</span>
        <span class="k">if</span> <span class="n">stop_loss_activated</span><span class="p">:</span>
            <span class="n">stop_loss_trigger_price</span><span class="p">,</span> <span class="n">stop_loss_execute_price</span> <span class="o">=</span> <span class="n">calculate_sl_stop_prices_usd</span><span class="p">(</span>
                <span class="n">order_side</span><span class="o">=</span><span class="n">order_side</span><span class="p">,</span>
                <span class="n">reference_price</span><span class="o">=</span><span class="n">reference_price</span><span class="p">,</span>
                <span class="n">sl_trigger_usd</span><span class="o">=</span><span class="n">sl_trigger_price_offset</span><span class="p">,</span>
                <span class="n">sl_execute_usd</span><span class="o">=</span><span class="n">sl_execution_price_offset</span><span class="p">,</span>
            <span class="p">)</span>
            <span class="n">order_request_dict</span><span class="o">.</span><span class="n">update</span><span class="p">(</span>
                <span class="n">slTriggerPx</span><span class="o">=</span><span class="n">stop_loss_trigger_price</span><span class="p">,</span>
                <span class="n">slOrdPx</span><span class="o">=</span><span class="n">stop_loss_execute_price</span><span class="p">,</span>
                <span class="n">slTriggerPxType</span><span class="o">=</span><span class="n">sl_trigger_price_type</span><span class="p">,</span>
                <span class="n">algoClOrdId</span><span class="o">=</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">generated_client_order_id</span><span class="si">}</span><span class="s1">TPORSL&#39;</span>
            <span class="p">)</span>

        <span class="n">order_placement_return</span> <span class="o">=</span> <span class="k">await</span> <span class="n">place_order</span><span class="p">(</span><span class="o">**</span><span class="n">order_request_dict</span><span class="p">)</span>

        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">order_placement_return</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>

        <span class="c1"># If error, cancel all orders and exit</span>
        <span class="k">if</span> <span class="n">order_placement_return</span> <span class="ow">and</span> <span class="n">order_placement_return</span><span class="o">.</span><span class="n">sCode</span> <span class="o">!=</span> <span class="s1">&#39;0&#39;</span><span class="p">:</span>
            <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">order_placement_return</span><span class="o">.</span><span class="n">sMsg</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="k">await</span> <span class="n">cancel_all_orders</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
            <span class="k">await</span> <span class="n">cancel_all_algo_orders_with_params</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">)</span>
            <span class="n">exit</span><span class="p">()</span>

        <span class="k">if</span> <span class="n">trailing_stop_loss_activated</span><span class="p">:</span>
            <span class="n">activePx</span> <span class="o">=</span> <span class="kc">None</span>
            <span class="k">if</span> <span class="n">trailing_stop_activation_price_offset</span><span class="p">:</span>
                <span class="n">activePx</span> <span class="o">=</span> <span class="n">reference_price</span> <span class="o">+</span> <span class="n">trailing_stop_activation_price_offset</span> <span class="k">if</span> <span class="n">order_side</span> <span class="o">==</span> <span class="s1">&#39;buy&#39;</span> <span class="k">else</span> \
                    <span class="n">reference_price</span> <span class="o">-</span> <span class="n">trailing_stop_activation_price_offset</span>

            <span class="c1"># Create Trailing Stop Loss</span>
            <span class="n">trailing_stop_order_placement_return</span> <span class="o">=</span> <span class="k">await</span> <span class="n">place_algo_trailing_stop_loss</span><span class="p">(</span>
                <span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">,</span>
                <span class="n">tdMode</span><span class="o">=</span><span class="n">TD_MODE</span><span class="p">,</span>
                <span class="n">ordType</span><span class="o">=</span><span class="s2">&quot;move_order_stop&quot;</span><span class="p">,</span>
                <span class="n">side</span><span class="o">=</span><span class="s1">&#39;buy&#39;</span> <span class="k">if</span> <span class="n">order_side</span> <span class="o">==</span> <span class="s1">&#39;sell&#39;</span> <span class="k">else</span> <span class="s1">&#39;sell&#39;</span><span class="p">,</span>
                <span class="n">sz</span><span class="o">=</span><span class="n">order_size</span><span class="p">,</span>
                <span class="n">activePx</span><span class="o">=</span><span class="n">activePx</span> <span class="ow">or</span> <span class="n">reference_price</span><span class="p">,</span>
                <span class="n">posSide</span><span class="o">=</span><span class="n">POSSIDETYPE</span><span class="p">,</span>
                <span class="n">callbackRatio</span><span class="o">=</span><span class="n">trailing_stop_callback_offset</span><span class="p">,</span>
                <span class="n">reduceOnly</span><span class="o">=</span><span class="s1">&#39;true&#39;</span><span class="p">,</span>
                <span class="n">algoClOrdId</span><span class="o">=</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">generated_client_order_id</span><span class="si">}</span><span class="s1">TrailS&#39;</span><span class="p">,</span>
                <span class="n">cxlOnClosePos</span><span class="o">=</span><span class="s2">&quot;true&quot;</span><span class="p">,</span>
            <span class="p">)</span>
            <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">trailing_stop_order_placement_return</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>

    <span class="k">if</span> <span class="n">dca_parameters</span> <span class="ow">and</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">dca_parameters</span><span class="p">,</span> <span class="nb">list</span><span class="p">):</span>
        <span class="n">dca_orders_to_call</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="n">_order_book</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">for</span> <span class="n">dca_order</span> <span class="ow">in</span> <span class="n">dca_parameters</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">dca_order</span><span class="o">.</span><span class="n">size</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">:</span>
                <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Ignoring DCA order with size </span><span class="si">{</span><span class="n">dca_order</span><span class="o">.</span><span class="n">size</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
                <span class="k">continue</span>

            <span class="n">dca_order_request_dict</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span>
                <span class="n">instId</span><span class="o">=</span><span class="n">instID</span><span class="p">,</span>
                <span class="n">side</span><span class="o">=</span><span class="nb">str</span><span class="p">(</span><span class="n">dca_order</span><span class="o">.</span><span class="n">side</span><span class="p">)</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span>
                <span class="n">tdMode</span><span class="o">=</span><span class="n">TD_MODE</span><span class="p">,</span>
                <span class="n">posSide</span><span class="o">=</span><span class="n">POSSIDETYPE</span><span class="p">,</span>
                <span class="n">sz</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">size</span><span class="p">,</span>
                <span class="n">ordType</span><span class="o">=</span><span class="s1">&#39;trigger&#39;</span><span class="p">,</span>
                <span class="n">triggerPx</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">trigger_price</span><span class="p">,</span>
                <span class="n">triggerPxType</span><span class="o">=</span><span class="s1">&#39;last&#39;</span><span class="p">,</span>
                <span class="n">orderPx</span><span class="o">=-</span><span class="mi">1</span><span class="p">,</span>  <span class="c1"># Default to market order, update downstream if not</span>
                <span class="n">algoClOrdId</span><span class="o">=</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">generate_random_string</span><span class="p">(</span><span class="mi">16</span><span class="p">,</span><span class="w"> </span><span class="s2">&quot;alphanumeric&quot;</span><span class="p">)</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s2">&quot;DCA&quot;</span><span class="si">}</span><span class="s1">&#39;</span>
            <span class="p">)</span>

            <span class="k">if</span> <span class="ow">not</span> <span class="n">_order_book</span> <span class="ow">and</span> <span class="n">dca_order</span><span class="o">.</span><span class="n">type</span> <span class="o">!=</span> <span class="s1">&#39;market&#39;</span><span class="p">:</span>
                <span class="n">_order_book</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_order_book</span><span class="p">(</span><span class="n">instID</span><span class="p">,</span> <span class="mi">400</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">dca_order</span><span class="o">.</span><span class="n">type</span> <span class="o">!=</span> <span class="s1">&#39;market&#39;</span><span class="p">:</span>
                <span class="n">dca_order_request_dict</span><span class="p">[</span><span class="s1">&#39;orderPx&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="k">await</span> <span class="n">prepare_limit_price</span><span class="p">(</span>
                    <span class="n">_order_book</span><span class="p">,</span> <span class="n">dca_order</span><span class="o">.</span><span class="n">size</span><span class="p">,</span>
                    <span class="nb">str</span><span class="p">(</span><span class="n">dca_order</span><span class="o">.</span><span class="n">side</span><span class="p">)</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span>
                    <span class="n">dca_order</span><span class="o">.</span><span class="n">execution_price</span><span class="p">,</span>
                    <span class="n">max_orderbook_price_offset</span><span class="o">=</span><span class="n">max_orderbook_limit_price_offset</span><span class="p">)</span>

            <span class="k">if</span> <span class="n">dca_order</span><span class="o">.</span><span class="n">tp_trigger_price_offset</span> <span class="ow">and</span> <span class="n">dca_order</span><span class="o">.</span><span class="n">tp_execution_price_offset</span><span class="p">:</span>
                <span class="n">stop_surplus_trigger_price</span><span class="p">,</span> <span class="n">stop_surplus_execute_price</span> <span class="o">=</span> <span class="n">calculate_tp_stop_prices_usd</span><span class="p">(</span>
                    <span class="n">order_side</span><span class="o">=</span><span class="nb">str</span><span class="p">(</span><span class="n">dca_order</span><span class="o">.</span><span class="n">side</span><span class="p">)</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span>
                    <span class="n">reference_price</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">execution_price</span><span class="p">,</span>
                    <span class="n">tp_trigger_usd</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">tp_trigger_price_offset</span><span class="p">,</span>
                    <span class="n">tp_execute_usd</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">tp_execution_price_offset</span><span class="p">,</span>
                <span class="p">)</span>
                <span class="n">dca_order_request_dict</span><span class="o">.</span><span class="n">update</span><span class="p">(</span>
                    <span class="n">tpTriggerPx</span><span class="o">=</span><span class="n">stop_surplus_trigger_price</span><span class="p">,</span>
                    <span class="n">tpOrdPx</span><span class="o">=</span><span class="n">stop_surplus_execute_price</span><span class="p">,</span>
                    <span class="n">tpTriggerPxType</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">tp_trigger_price_type</span><span class="p">,</span>
                <span class="p">)</span>
            <span class="k">if</span> <span class="n">dca_order</span><span class="o">.</span><span class="n">sl_trigger_price_offset</span> <span class="ow">and</span> <span class="n">dca_order</span><span class="o">.</span><span class="n">sl_execution_price_offset</span><span class="p">:</span>
                <span class="n">stop_loss_trigger_price</span><span class="p">,</span> <span class="n">stop_loss_execute_price</span> <span class="o">=</span> <span class="n">calculate_sl_stop_prices_usd</span><span class="p">(</span>
                    <span class="n">order_side</span><span class="o">=</span><span class="nb">str</span><span class="p">(</span><span class="n">dca_order</span><span class="o">.</span><span class="n">side</span><span class="p">)</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span>
                    <span class="n">reference_price</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">execution_price</span><span class="p">,</span>
                    <span class="n">sl_trigger_usd</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">sl_trigger_price_offset</span><span class="p">,</span>
                    <span class="n">sl_execute_usd</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">sl_execution_price_offset</span><span class="p">,</span>
                <span class="p">)</span>
                <span class="n">dca_order_request_dict</span><span class="o">.</span><span class="n">update</span><span class="p">(</span>
                    <span class="n">slTriggerPx</span><span class="o">=</span><span class="n">stop_loss_trigger_price</span><span class="p">,</span>
                    <span class="n">slOrdPx</span><span class="o">=</span><span class="n">stop_loss_execute_price</span><span class="p">,</span>
                    <span class="n">slTriggerPxType</span><span class="o">=</span><span class="n">dca_order</span><span class="o">.</span><span class="n">sl_trigger_price_type</span><span class="p">,</span>
                <span class="p">)</span>

            <span class="n">dca_orders_to_call</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">dca_order_request_dict</span><span class="p">)</span>

        <span class="n">dca_orders_placement_return</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span>
            <span class="o">*</span><span class="p">[</span><span class="n">place_algo_order</span><span class="p">(</span><span class="o">**</span><span class="n">dca_order</span><span class="p">)</span> <span class="k">for</span> <span class="n">dca_order</span> <span class="ow">in</span> <span class="n">dca_orders_to_call</span><span class="p">]</span>
        <span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">dca_orders_placement_return</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n\n</span><span class="s1">FINAL REPORT&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="k">await</span> <span class="n">fetch_status_report_for_instrument</span><span class="p">(</span><span class="n">instID</span><span class="p">,</span> <span class="n">TD_MODE</span><span class="p">)</span></div>



<div class="viewcode-block" id="fetch_fill_history">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.fetch_fill_history">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">fetch_fill_history</span><span class="p">(</span><span class="n">start_timestamp</span><span class="p">,</span> <span class="n">end_timestamp</span><span class="p">,</span> <span class="n">instType</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Fetches the fill history for a specific period and instrument type.</span>

<span class="sd">    :param start_timestamp: The starting timestamp for the fill history.</span>
<span class="sd">    :type start_timestamp: int</span>
<span class="sd">    :param end_timestamp: The ending timestamp for the fill history.</span>
<span class="sd">    :type end_timestamp: int</span>
<span class="sd">    :param instType: The type of instrument for the fill history, defaults to </span>
<span class="sd">    :type instType: str, optional</span>
<span class="sd">    :returns: A list of fill entries.</span>
<span class="sd">    :raises AssertionError: If the requested period is outside the allowed range based on the instrument type.</span>
<span class="sd">    &quot;&quot;&quot;</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>

<span class="sd">    Note:</span>
<span class="sd">        If instType passed in then up to 30 days ago the data can be pulled, but if None then only up to 3 days, verify</span>
<span class="sd">            Im refering to AGO!!! meaning from now</span>

<span class="sd">    :param start_timestamp:</span>
<span class="sd">    :param end_timestamp:</span>
<span class="sd">    :param instType:</span>
<span class="sd">    :return:</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">instType</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="k">assert</span> <span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_timestamp</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">259200</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">start_timestamp</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">assert</span> <span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_timestamp</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">2592000</span><span class="p">,</span> <span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">start_timestamp</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span>

    <span class="n">limit</span> <span class="o">=</span> <span class="mi">100</span>
    <span class="n">after</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
    <span class="n">all_data</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">request_count</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">start_time</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>

    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>

        <span class="k">try</span><span class="p">:</span>
            <span class="n">fills_response</span> <span class="o">=</span> <span class="n">tradeAPI</span><span class="o">.</span><span class="n">get_fills_history</span><span class="p">(</span>
                <span class="n">instType</span><span class="o">=</span><span class="n">instType</span><span class="p">,</span>
                <span class="n">uly</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span>
                <span class="n">instId</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span>
                <span class="n">ordId</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span>
                <span class="n">after</span><span class="o">=</span><span class="n">after</span><span class="p">,</span>
                <span class="n">before</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span>
                <span class="n">limit</span><span class="o">=</span><span class="n">limit</span><span class="p">,</span>
                <span class="n">instFamily</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span>
                <span class="n">begin</span><span class="o">=</span><span class="n">start_timestamp</span><span class="p">,</span>
                <span class="n">end</span><span class="o">=</span><span class="n">end_timestamp</span>
            <span class="p">)</span>
            <span class="k">if</span> <span class="n">fills_response</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;code&#39;</span><span class="p">)</span> <span class="o">!=</span> <span class="s1">&#39;0&#39;</span><span class="p">:</span>
                <span class="k">break</span>

            <span class="n">fills_message_data</span> <span class="o">=</span> <span class="n">fills_response</span><span class="p">[</span><span class="s1">&#39;data&#39;</span><span class="p">]</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">fills_message_data</span><span class="p">:</span>
                <span class="k">break</span>  <span class="c1"># Break if no data is returned</span>

            <span class="n">all_data</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">fills_message_data</span><span class="p">)</span>

            <span class="c1"># Check if we have reached the start_timestamp</span>
            <span class="k">if</span> <span class="nb">int</span><span class="p">(</span><span class="n">fills_message_data</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">][</span><span class="s1">&#39;ts&#39;</span><span class="p">])</span> <span class="o">&lt;=</span> <span class="n">start_timestamp</span><span class="p">:</span>
                <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Found the start_timestamp: </span><span class="si">{</span><span class="n">start_timestamp</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
                <span class="k">break</span>  <span class="c1"># Exit the loop if we have reached the start_timestamp</span>

            <span class="n">after</span> <span class="o">=</span> <span class="n">fills_message_data</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">][</span><span class="s1">&#39;billId&#39;</span><span class="p">]</span>  <span class="c1"># Prepare the &#39;after&#39; for the next request</span>
            <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">after</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="n">request_count</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="k">if</span> <span class="n">request_count</span> <span class="o">%</span> <span class="mi">10</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                <span class="n">elapsed</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">start_time</span>
                <span class="k">if</span> <span class="n">elapsed</span> <span class="o">&lt;</span> <span class="mi">2</span><span class="p">:</span>
                    <span class="c1"># time.sleep(2 - elapsed)</span>
                    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">2</span> <span class="o">-</span> <span class="n">elapsed</span><span class="p">)</span>
                <span class="n">start_time</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>

            <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>  <span class="c1"># FIXME Here to prevent hogging the CPU remove this line</span>



        <span class="k">except</span> <span class="n">HTTPError</span> <span class="k">as</span> <span class="n">http_err</span><span class="p">:</span>
            <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;HTTP error occurred: </span><span class="si">{</span><span class="n">http_err</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="k">break</span>  <span class="c1"># Optional: Decide whether to break or retry</span>
        <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
            <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Other error occurred: </span><span class="si">{</span><span class="n">err</span><span class="si">}</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="k">break</span>  <span class="c1"># Optional: Decide whether to break or retry</span>

    <span class="k">return</span> <span class="p">[</span><span class="n">FillEntry</span><span class="p">(</span><span class="o">**</span><span class="n">fill</span><span class="p">)</span> <span class="k">for</span> <span class="n">fill</span> <span class="ow">in</span> <span class="n">all_data</span><span class="p">]</span></div>



<div class="viewcode-block" id="okx_premium_indicator_handler">
<a class="viewcode-back" href="../../pyokx.rest_handling.html#pyokx.rest_handling.okx_premium_indicator_handler">[docs]</a>
<span class="k">async</span> <span class="k">def</span> <span class="nf">okx_premium_indicator_handler</span><span class="p">(</span><span class="n">indicator_input</span><span class="p">:</span> <span class="n">Union</span><span class="p">[</span><span class="n">OKXPremiumIndicatorSignalRequestForm</span><span class="p">,</span> <span class="nb">dict</span><span class="p">]):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Handles incoming premium indicator signals for trading on the OKX platform. It processes the signals,</span>
<span class="sd">    interprets the trading instructions, manages positions based on the received signals, and executes trading actions.</span>

<span class="sd">    :param indicator_input: The input containing the signals and parameters from the premium indicator.</span>
<span class="sd">                            This can be an instance of PremiumIndicatorSignalRequestForm or a dictionary</span>
<span class="sd">                            that corresponds to the structure of PremiumIndicatorSignalRequestForm.</span>
<span class="sd">    :type indicator_input: OKXPremiumIndicatorSignalRequestForm or dict</span>

<span class="sd">    :returns: A dictionary detailing the outcome of the signal processing. If the processing is successful, it includes</span>
<span class="sd">              the &#39;instrument_status_report&#39; which is a comprehensive status report of the instrument after handling the signal.</span>
<span class="sd">              In case of an error, it returns a message detailing the issue.</span>

<span class="sd">    Process Flow:</span>
<span class="sd">    1. Validates the input type and converts it into PremiumIndicatorSignalRequestForm if necessary.</span>
<span class="sd">    2. Extracts and processes trading signals (like Bearish, Bullish, and their respective exit signals) from the input.</span>
<span class="sd">    3. Determines the trading action (buy/sell) based on the processed signals.</span>
<span class="sd">    4. Fetches the current positions for the given instrument ID and aligns them with the received signals.</span>
<span class="sd">    5. Prepares the trading action by setting order sides, clearing prior orders if needed, and handling the &#39;red_button&#39; emergency stop.</span>
<span class="sd">    6. Passes the processed signal to `okx_signal_handler` for executing the trading operations on the OKX platform.</span>
<span class="sd">    7. Returns a success message with the &#39;instrument_status_report&#39; or an error message in case of an exception.</span>

<span class="sd">    :raises Exception: Catches and logs any exceptions that occur during the processing of the signal, returning a detailed error message.</span>

<span class="sd">    Note:</span>
<span class="sd">    The major difference between the `okx_signal_handler` and `okx_premium_indicator` is that the latter is</span>
<span class="sd">    specifically designed to handle premium indicator signals (TV), and it includes additional processing</span>
<span class="sd">    steps for interpreting the signals and aligning them with the current positions.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">indicator_input</span><span class="p">,</span> <span class="n">OKXPremiumIndicatorSignalRequestForm</span><span class="p">):</span>
        <span class="n">input_to_pass</span> <span class="o">=</span> <span class="n">indicator_input</span><span class="o">.</span><span class="n">model_dump</span><span class="p">()</span>
    <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">indicator_input</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span>
        <span class="n">input_to_pass</span> <span class="o">=</span> <span class="n">indicator_input</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="p">{</span><span class="s2">&quot;detail&quot;</span><span class="p">:</span> <span class="sa">f</span><span class="s2">&quot;Invalid input type </span><span class="si">{</span><span class="nb">type</span><span class="p">(</span><span class="n">indicator_input</span><span class="p">)</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">}</span>

    <span class="n">indicator_input</span> <span class="o">=</span> <span class="n">OKXPremiumIndicatorSignalRequestForm</span><span class="p">(</span><span class="o">**</span><span class="n">input_to_pass</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">pprint</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">indicator_input</span><span class="o">.</span><span class="n">OKXSignalInput</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="n">pprint</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">indicator_input</span><span class="o">.</span><span class="n">PremiumIndicatorSignals</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>

        <span class="c1"># Interpret Signals</span>
        <span class="n">premium_indicator</span> <span class="o">=</span> <span class="n">indicator_input</span><span class="o">.</span><span class="n">PremiumIndicatorSignals</span>

        <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish</span><span class="p">)</span>
        <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish_plus</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish_plus</span><span class="p">)</span>
        <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish</span><span class="p">)</span>
        <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish_plus</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish_plus</span><span class="p">)</span>
        <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish_Exit</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">if</span> <span class="p">(</span><span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish_Exit</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;null&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="kc">None</span><span class="p">])</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span>
            <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish_Exit</span><span class="p">)</span>
        <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish_Exit</span> <span class="o">=</span> <span class="mi">0</span> <span class="k">if</span> <span class="p">(</span><span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish_Exit</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;null&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="kc">None</span><span class="p">])</span> <span class="k">else</span> <span class="nb">float</span><span class="p">(</span>
            <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish_Exit</span><span class="p">)</span>

        <span class="n">_order_side</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="n">_close_signal</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="n">_red_button</span> <span class="o">=</span> <span class="n">indicator_input</span><span class="o">.</span><span class="n">OKXSignalInput</span><span class="o">.</span><span class="n">red_button</span>
        <span class="k">if</span> <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish</span> <span class="ow">or</span> <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish_plus</span><span class="p">:</span>
            <span class="n">_order_side</span> <span class="o">=</span> <span class="s1">&#39;sell&#39;</span>
        <span class="k">elif</span> <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish</span> <span class="ow">or</span> <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish_plus</span><span class="p">:</span>
            <span class="n">_order_side</span> <span class="o">=</span> <span class="s1">&#39;buy&#39;</span>
        <span class="k">if</span> <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bearish_Exit</span><span class="p">:</span>
            <span class="n">_close_signal</span> <span class="o">=</span> <span class="s1">&#39;exit_sell&#39;</span>
        <span class="k">elif</span> <span class="n">premium_indicator</span><span class="o">.</span><span class="n">Bullish_Exit</span><span class="p">:</span>
            <span class="n">_close_signal</span> <span class="o">=</span> <span class="s1">&#39;exit_buy&#39;</span>

        <span class="n">instId_positions</span> <span class="o">=</span> <span class="k">await</span> <span class="n">get_all_positions</span><span class="p">(</span><span class="n">instId</span><span class="o">=</span><span class="n">indicator_input</span><span class="o">.</span><span class="n">OKXSignalInput</span><span class="o">.</span><span class="n">instID</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">instId_positions</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">current_position</span> <span class="o">=</span> <span class="n">instId_positions</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
            <span class="n">current_position_side</span> <span class="o">=</span> <span class="s1">&#39;buy&#39;</span> <span class="k">if</span> <span class="nb">float</span><span class="p">(</span><span class="n">current_position</span><span class="o">.</span><span class="n">pos</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="k">else</span> <span class="s1">&#39;sell&#39;</span> <span class="k">if</span> <span class="nb">float</span><span class="p">(</span>
                <span class="n">current_position</span><span class="o">.</span><span class="n">pos</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span> <span class="k">else</span> <span class="kc">None</span>  <span class="c1"># we are only using net so only one position</span>

            <span class="k">if</span> <span class="n">_close_signal</span><span class="p">:</span>
                <span class="n">buy_exit</span> <span class="o">=</span> <span class="n">_close_signal</span> <span class="o">==</span> <span class="s1">&#39;exit_buy&#39;</span> <span class="ow">and</span> <span class="n">current_position_side</span> <span class="o">==</span> <span class="s1">&#39;buy&#39;</span>
                <span class="n">sell_exit</span> <span class="o">=</span> <span class="n">_close_signal</span> <span class="o">==</span> <span class="s1">&#39;exit_sell&#39;</span> <span class="ow">and</span> <span class="n">current_position_side</span> <span class="o">==</span> <span class="s1">&#39;sell&#39;</span>
                <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">buy_exit</span> <span class="ow">or</span> <span class="n">sell_exit</span><span class="p">):</span>
                    <span class="n">_close_signal</span> <span class="o">=</span> <span class="kc">None</span>

        <span class="c1"># TODO - IDEA: Logic here betweeen _close_signal and entry, if just a closing then it can be handled using market or limit orders but if it is an entry and exit then we decide depening on wehther the entry is in the same or opposite directoion and if flip on opposite order is true.</span>
        <span class="c1">#   lets assume that we are not flipping on opposite order  then cancel if entry in opposite direction and close_order then clear before starting, if just closing then trat them as an actual order which can be market post only or limits</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">_order_side</span><span class="w"> </span><span class="ow">or</span><span class="w"> </span><span class="n">_close_signal</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">_red_button</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">_order_side</span> <span class="ow">or</span> <span class="n">_close_signal</span> <span class="ow">or</span> <span class="n">_red_button</span><span class="p">:</span>
            <span class="n">okx_signal</span> <span class="o">=</span> <span class="n">indicator_input</span><span class="o">.</span><span class="n">OKXSignalInput</span>

            <span class="n">okx_signal</span><span class="o">.</span><span class="n">order_side</span> <span class="o">=</span> <span class="n">_order_side</span> <span class="k">if</span> <span class="n">_order_side</span> <span class="k">else</span> <span class="s1">&#39;&#39;</span>
            <span class="n">okx_signal</span><span class="o">.</span><span class="n">clear_prior_to_new_order</span> <span class="o">=</span> <span class="kc">True</span> <span class="k">if</span> <span class="n">okx_signal</span><span class="o">.</span><span class="n">clear_prior_to_new_order</span> <span class="ow">or</span> <span class="n">_close_signal</span> <span class="k">else</span> <span class="kc">False</span>

            <span class="k">if</span> <span class="n">_close_signal</span><span class="p">:</span>  <span class="c1"># FIXME this works for Premium indicator but might have issues if not handled in order</span>
                <span class="n">okx_signal</span><span class="o">.</span><span class="n">order_side</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>

            <span class="n">pprint</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;updated-</span><span class="si">{</span><span class="n">premium_indicator</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
            <span class="n">pprint</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;updated-</span><span class="si">{</span><span class="n">okx_signal</span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>

            <span class="k">assert</span> <span class="n">indicator_input</span><span class="o">.</span><span class="n">OKXSignalInput</span><span class="p">,</span> <span class="s2">&quot;OKXSignalInput is None&quot;</span>
            <span class="n">okx_signal_input</span> <span class="o">=</span> <span class="n">indicator_input</span><span class="o">.</span><span class="n">OKXSignalInput</span>
            <span class="n">instrument_status_report</span><span class="p">:</span> <span class="n">InstrumentStatusReport</span> <span class="o">=</span> <span class="k">await</span> <span class="n">okx_signal_handler</span><span class="p">(</span><span class="o">**</span><span class="n">okx_signal_input</span><span class="o">.</span><span class="n">model_dump</span><span class="p">())</span>
            <span class="n">pprint</span><span class="p">(</span><span class="n">instrument_status_report</span><span class="p">)</span>
            <span class="k">assert</span> <span class="n">instrument_status_report</span><span class="p">,</span> <span class="s2">&quot;Instrument Status Report is None, check the Instrument ID&quot;</span>
            <span class="k">return</span> <span class="p">{</span><span class="s2">&quot;detail&quot;</span><span class="p">:</span> <span class="s2">&quot;okx signal received&quot;</span><span class="p">,</span> <span class="s2">&quot;instrument_status_report&quot;</span><span class="p">:</span> <span class="n">instrument_status_report</span><span class="p">}</span>
        <span class="k">return</span> <span class="p">{</span><span class="s2">&quot;detail&quot;</span><span class="p">:</span> <span class="s2">&quot;okx signal received but no action taken&quot;</span><span class="p">}</span>
    <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;Exception in okx_premium_indicator </span><span class="si">{</span><span class="n">e</span><span class="si">}</span><span class="s2">&quot;</span><span class="p">)</span>
        <span class="k">return</span> <span class="p">{</span><span class="s2">&quot;detail&quot;</span><span class="p">:</span> <span class="s2">&quot;okx signal received but there was an exception, check the logs&quot;</span><span class="p">,</span> <span class="s2">&quot;exception&quot;</span><span class="p">:</span> <span class="nb">str</span><span class="p">(</span><span class="n">e</span><span class="p">)}</span></div>



<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">dotenv</span>

    <span class="n">dotenv</span><span class="o">.</span><span class="n">load_dotenv</span><span class="p">(</span><span class="n">dotenv</span><span class="o">.</span><span class="n">find_dotenv</span><span class="p">())</span>

    <span class="c1"># Define the test function to be used</span>
    <span class="n">TEST_FUNCTION</span> <span class="o">=</span> <span class="s1">&#39;okx_premium_indicator&#39;</span>

    <span class="c1"># Immediately execute the &#39;red button&#39; functionality to clear all positions and orders</span>
    <span class="c1"># TODO: Ensure only relevant orders/positions are handled.</span>
    <span class="c1"># asyncio.run(okx_signal_handler(red_button=True))</span>

    <span class="c1"># Branching logic based on the test function chosen</span>
    <span class="k">if</span> <span class="n">TEST_FUNCTION</span> <span class="o">==</span> <span class="s1">&#39;okx_signal_handler&#39;</span><span class="p">:</span>
        <span class="c1"># Execute the &#39;okx_signal_handler&#39; with predefined parameters for testing</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">okx_signal_handler</span><span class="p">(</span>
            <span class="c1"># Global</span>
            <span class="n">instID</span><span class="o">=</span><span class="s2">&quot;BTC-USDT-240628&quot;</span><span class="p">,</span>
            <span class="n">leverage</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span>
            <span class="n">max_orderbook_limit_price_offset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
            <span class="n">clear_prior_to_new_order</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
            <span class="n">red_button</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
            <span class="c1"># Principal Order</span>
            <span class="n">usd_order_size</span><span class="o">=</span><span class="mi">100</span><span class="p">,</span>
            <span class="n">order_side</span><span class="o">=</span><span class="s2">&quot;BUY&quot;</span><span class="p">,</span>
            <span class="n">order_type</span><span class="o">=</span><span class="s2">&quot;MARKET&quot;</span><span class="p">,</span>
            <span class="n">flip_position_if_opposite_side</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
            <span class="c1"># Principal Order&#39;s TP/SL/Trail</span>
            <span class="c1"># tp_trigger_price_offset=100,</span>
            <span class="c1"># tp_execution_price_offset=90,</span>
            <span class="c1"># sl_trigger_price_offset=100,</span>
            <span class="c1"># sl_execution_price_offset=90,</span>
            <span class="c1"># trailing_stop_activation_price_offset=100,</span>
            <span class="c1"># trailing_stop_callback_offset=10,</span>
            <span class="c1"># DCA Orders (are not linked to the principal order)</span>
            <span class="c1"># dca_parameters=[</span>
            <span class="c1">#     DCAInputParameters(</span>
            <span class="c1">#         usd_amount=100,</span>
            <span class="c1">#         order_type=&quot;LIMIT&quot;,</span>
            <span class="c1">#         order_side=&quot;BUY&quot;,</span>
            <span class="c1">#         trigger_price_offset=100,</span>
            <span class="c1">#         execution_price_offset=90,</span>
            <span class="c1">#         tp_trigger_price_offset=100,</span>
            <span class="c1">#         tp_execution_price_offset=90,</span>
            <span class="c1">#         sl_trigger_price_offset=100,</span>
            <span class="c1">#         sl_execution_price_offset=90</span>
            <span class="c1">#     ),</span>
            <span class="c1">#     DCAInputParameters(</span>
            <span class="c1">#         usd_amount=100,</span>
            <span class="c1">#         order_type=&quot;LIMIT&quot;,</span>
            <span class="c1">#         order_side=&quot;BUY&quot;,</span>
            <span class="c1">#         trigger_price_offset=150,</span>
            <span class="c1">#         execution_price_offset=149,</span>
            <span class="c1">#         tp_trigger_price_offset=100,</span>
            <span class="c1">#         tp_execution_price_offset=90,</span>
            <span class="c1">#         sl_trigger_price_offset=100,</span>
            <span class="c1">#         sl_execution_price_offset=90</span>
            <span class="c1">#     )</span>
            <span class="c1"># ]</span>
        <span class="p">))</span>
    <span class="k">elif</span> <span class="n">TEST_FUNCTION</span> <span class="o">==</span> <span class="s1">&#39;okx_premium_indicator&#39;</span><span class="p">:</span>
        <span class="c1"># Load a payload from a file for testing the &#39;okx_premium_indicator&#39;</span>
        <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;../tradingview_tools/tradingview_debug_message.json&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
            <span class="n">webhook_payload</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>

        <span class="c1"># Construct the signal request form</span>
        <span class="n">indicator_input</span> <span class="o">=</span> <span class="n">OKXPremiumIndicatorSignalRequestForm</span><span class="p">(</span><span class="o">**</span><span class="n">webhook_payload</span><span class="p">)</span>


        <span class="c1"># Process the indicator input and store the result</span>
        <span class="c1"># response = asyncio.run(okx_premium_indicator_handler(indicator_input))</span>

        <span class="c1"># Optionally Use a request instead of calling the function directly</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">post</span><span class="p">(</span>
            <span class="c1"># &#39;http://localhost:8080/tradingview/premium_indicator/&#39;, # Local</span>
            <span class="c1"># &#39;http://localhost/api/tradingview/premium_indicator&#39;, # Docker</span>
            <span class="s1">&#39;http://34.170.145.146/api/tradingview/premium_indicator&#39;</span><span class="p">,</span> <span class="c1"># GCP</span>
            <span class="c1"># &#39;http://34.170.145.146:8080/tradingview/premium_indicator/&#39;, # GCP</span>
                                 <span class="n">json</span><span class="o">=</span><span class="n">indicator_input</span><span class="o">.</span><span class="n">model_dump</span><span class="p">()</span>
        <span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">response</span><span class="o">.</span><span class="n">content</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">json</span><span class="p">()</span>



    <span class="k">else</span><span class="p">:</span>
        <span class="c1"># Handle invalid test function selection</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Invalid test function </span><span class="si">{</span><span class="n">TEST_FUNCTION</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>

    <span class="c1"># Print the final response for debugging</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">response</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>

    <span class="c1"># Validation and print statements for the instrument status report</span>
    <span class="k">if</span> <span class="n">response</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;No response&quot;</span><span class="p">)</span>
        <span class="n">exit</span><span class="p">()</span>

    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="n">InstrumentStatusReport</span><span class="p">):</span>
        <span class="n">instrument_report</span> <span class="o">=</span> <span class="n">response</span>
    <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span>
        <span class="n">instrument_report</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;instrument_status_report&#39;</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">instrument_report</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;No instrument status report&quot;</span><span class="p">)</span>
            <span class="n">exit</span><span class="p">()</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;No instrument status report&quot;</span><span class="p">)</span>
        <span class="n">exit</span><span class="p">()</span>

    <span class="c1"># Debugging print statements for the instrument report</span>
    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">instrument_report</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">pprint</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">instrument_report</span><span class="o">.</span><span class="n">positions</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">pprint</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">instrument_report</span><span class="o">.</span><span class="n">positions</span><span class="p">)</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">pprint</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">instrument_report</span><span class="o">.</span><span class="n">positions</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">pos</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">pprint</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">instrument_report</span><span class="o">.</span><span class="n">orders</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">pprint</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;</span><span class="si">{</span><span class="n">instrument_report</span><span class="o">.</span><span class="n">algo_orders</span><span class="w"> </span><span class="si">= }</span><span class="s1">&#39;</span><span class="p">)</span>
</pre></div>

           </div>
          </div>
          <footer>

  <hr/>

  <div role="contentinfo">
    <p>&#169; Copyright 2024, Ruben Fernandez Carbon.</p>
  </div>

  Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a
    <a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
    provided by <a href="https://readthedocs.org">Read the Docs</a>.
   

</footer>
        </div>
      </div>
    </section>
  </div>
  <script>
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script> 

</body>
</html>